<?php
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Between;
use Phalcon\Validation\Validator\StringLength;

class MonitorController extends CloudControllerBase
{

    /******************************   云播    ***********************************************************/

    public function detail4fixAction()
    {
        ini_set('default_socket_timeout', -1);
        $playType = 0;
        //分页大小
        $psize = '5000';
        $flightMissionId = $this->request->get('fmid');
        $flightMissionId = intval($flightMissionId);
        $local_id = $this->request->get('local_id');

        if (empty($flightMissionId)) {
            if (!empty($local_id)) {
                $sql = "select * from flight_mission where local_id='$local_id'";
                $flightMissInfo = $this->fetchOne($sql);
                $flightMissionId = $flightMissInfo['id'];
            }
        } else {
            //获取flightmission信息
            $flightMissInfo = $this->fetchOne(
                "select * from flight_mission where id=$flightMissionId"
            );
        }
        if (empty($flightMissionId)) {
            $this->transferErrorPage("飞行记录错误", "当前飞行记录未找到");
        }


        //判断当前是否为正在飞行
        if ($this->isMissionFlying($flightMissionId)) {
            $playType = 1;
        } else {
            //获取所有飞行记录
            if (FALSE === strpos('FF', $flightMissInfo['task_coordinate_waypoints'])) {
                $task_coordinate_waypoints = explode('FF', $flightMissInfo['task_coordinate_waypoints']);
                $flightMissInfo['task_coordinate_waypoints'] = $task_coordinate_waypoints[0];
            }
            $created_at_time=strtotime($flightMissInfo["created_at"]);
//            $packages=$this->dbFlightLogProxy->fetchAll("flight_mission_id=$flightMissionId order by id asc",$created_at_time);
//            $sql = "select * from flight_monitor_detail_log where flight_mission_id = $flightMissionId order by id asc";
//            $packages = $this->fetchAll($sql);
            if(!$this->redis->exists("detail_log-".$flightMissInfo['local_id'])) {
                $sql = "select * from detail_transform_log where flight_mission_id=$flightMissionId";
                $transform_id = $this->fetchOne($sql);
                if($transform_id){
                    $str = "http://files-10008291.file.myqcloud.com{$this->host['log_file']}{$flightMissInfo['local_id']}.json";
                    $mtime=explode(' ',microtime());
                    file_put_contents("./log_" . date("Y-m-d") . ".txt","\n".date("H:i:s", time()).':'.__METHOD__.':'."url:$str, time:{$mtime[1]}.{$mtime[0]}", FILE_APPEND);
                    $result=file_get_contents("http://files-10008291.file.myqcloud.com{$this->host['log_file']}{$flightMissInfo['id']}.json");

                    $packages=json_decode($result,true);
                    $this->package->getPackagesInfo($packages);
                }else{
                    $packages=$this->dbFlightLogProxy->fetchAll("flight_mission_id=$flightMissionId order by id asc",$created_at_time);
                    //$sql = "select * from flight_monitor_detail_log where flight_mission_id = $flightMissionId order by id asc";
                    //$packages = $this->fetchAll($sql);
                    $this->package->getPackagesInfo($packages);
                }

                $packages_arr = array();
                foreach($packages as $key=>$value ){
                    if(!isset($packages_arr[floor($value['created_str']/1000)]))
                        $packages_arr[floor($value['created_str']/1000)] = $key;
                }

                $json = array( 'packages' => $packages, 'time' => $packages_arr );
                if(count($packages)<50000){
                    $redis_json = json_encode ($json);
                    if ($redis_json){
                        $this->redis->setex( "detail_log-".$flightMissInfo['local_id'], 14400, json_encode ( $json) );
                    }else {
                        $ret = json_last_error();
                        $this->return403();
                    }
                }
            }else{
                $json = $this->redis->get("detail_log-".$flightMissInfo['local_id']);
                $packages = json_decode($json,1)['packages'];
            }

            if (count($packages) > 0) {
                $startPack = $packages[0];
                $endPack = end($packages);

                $packages = array_chunk($packages, $psize);
            } else {
                $packages = array();
                $startPack['created_str'] = 0;
                $endPack['created_str'] = 0;
            }

            if (!empty($packages))
                foreach ($packages as &$pack)
                    $pack = json_encode($pack);

            $recorderDataSql = "SELECT * FROM flight_data WHERE flight_mission_id='$local_id' ORDER BY created_at ASC";
            $recorderData = $this->fetchAll($recorderDataSql);


        }

        $taskInfo = $this->fetchOne('select * from flight_task where flight_task_guid=\'' . $flightMissInfo['flight_task_id'] . '\'');

        $uasInfo = $this->fetchAll("select * from uas_status where flight_mission_id ='{$flightMissInfo['id']}' order by id asc");

        if (!empty($uasInfo[0]['uas_serial_id'])) {
            $planeInfo = $this->fetchOne("select * from plane where uas_serial_id='{$uasInfo[0]['uas_serial_id']}'");
            $lastUas = $this->fetchOne("select * from uas_status where uas_serial_id ='{$uasInfo[0]['uas_serial_id']}' order by id desc limit 1");
        } else {
            $planeInfo = [];
            $lastUas = [];
        }

        if (!empty($planeInfo['id'])) {
            $planeReport = $this->fetchOne("select * from report_factory_set where plane_id ={$planeInfo['id']}");
            $keyInfo = $this->fetchOne("select * from plane_key where plane_id='{$planeInfo['id']}'");
        } else {
            $planeReport = [];
            $keyInfo = [];
        }

        $planeWayCS="wgs84";

        if(!$this->isProjectUseWgs84ByLocalId($flightMissInfo["project_id"]))
        {
            $planeWayCS="gcj02";
        }
        $curLocationCS="wgs84";
        if($flightMissInfo["plane_type"]=="D1000"||
            $flightMissInfo["plane_type"]=="Phantom 4 Pro" ||
            $flightMissInfo["plane_type"]=="Inspire 2"
        ){
            $curLocationCS="gcj02";
            $planeWayCS="gcj02";
        }

        //获取阿里云播放地址
        try
        {
            $curl_data = array("mission_id" => $local_id);
            if ($playType == 1){
                $curl_path = $this->host["api_host"]."/rtmp/aliCloudGetPullChannel";
                $token = $this->getMonitorLoginUser()->token;
            }else {
                $curl_path = $this->host["api_host"]."/rtmp/aliCloudGetRecordFile";
                $userId = $this->getMonitorLoginUser()->userId;
                $cloudTokenSql = "SELECT token FROM user WHERE id=$userId";
                $cloudTokenData = $this->fetchOne($cloudTokenSql);
                $token = $cloudTokenData["token"];
            }
            $header = array("token: ". $token);
            $result = $this->curlRequest( $curl_path, "post", $curl_data, $header);
            $resultArr = json_decode($result, true);
            if ($resultArr["status"] == 0){
                $rtmp = json_encode($resultArr["data"]);
            }else {
                $rtmp = "";
            }
        }
        catch (Exception $e){
            $rtmp = "";
        }


        $this->view->setVars(array(
            'packages' => $packages,
            'startTime' => $startPack['created_str'],
            'endTime' => $endPack['created_str'],
            'flightMissionInfo' => json_encode($flightMissInfo),
            'flightMission' => $flightMissInfo,
            'playType' => $playType,
            'taskInfo' => $taskInfo,
            'planeInfo' => $planeInfo,
            'uasInfo' => $uasInfo,
            'planeReport' => $planeReport,
            'keyInfo' => $keyInfo,
            'lastUas' => $lastUas,
            "planeWayCS"=>$planeWayCS,
            "locationCS"=>$curLocationCS,
            'socket' => $this->host['missionSocket'],
            "recorderDataSocket" => $this->host['dataRecorderSocket'],
            "recorderData" => json_encode($recorderData),
            "videoPlayPath" => $rtmp
        ));
    }

    public function detail4mobileAction()
    {
        $this->detail4fixAction();
    }
    public function detail4fixPhoneAction(){

        $this->detail4fixAction();
    }
    public function detail4mobilePhoneAction(){
        $this->detail4fixAction();
    }


    /**
     * 是否在飞行
     * @param $mission_id missionId
     * @return bool
     */
    private function isMissionFlying($mission_id)
    {

        $sql = $this->getIsFlyingSql(" id=$mission_id");
        $data = $this->fetchOne($sql);
        if ($data['total'] > 0) {
            if($this->redis->exists('detail-upload-fmid-'.$data['local_id'])){
                return true;
            }else{
                return false;
            }
        }
        return false;
    }

    /**
     *
     * @param $filter
     */
    private function getIsFlyingSql($filter)
    {
        $timeInterval = -2;
        $sql = "SELECT count(*) as total,local_id 
FROM (SELECT
        m.id,
        m.project_id,m.local_id,
        m.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name,flight_task_id,
        count(*) AS flight_count
      FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id
      WHERE NOT u.id IS NULL
      GROUP BY m.id) AS temp
WHERE created_at >= date_add(now(), INTERVAL $timeInterval HOUR) AND flight_count = 1
  and $filter";
        return $sql;
    }






    const ZOOM_SPAN_LEVEL_WIDTH = 277.3;
    const ZOOM_SPAN_LEVEL_HEIGHT = 277.3;
    //lat 维度 横
    //lng 经度 su
    public function getMissionListAction()
    {
        $summarize = $this->getPost("summarize");
        $leftFrom = $this->getPost("leftFrom");
        $leftTo = $this->getPost("leftTo");
        $topFrom = $this->getPost("topFrom");
        $topTo = $this->getPost("topTo");
        $zoom = $this->getPost("zoom");

        if ($leftFrom && $leftTo && $topFrom && $topTo) {

            $resultArray = array();
            if ($summarize) {

                //区分对待
                $spanWidth = $this::ZOOM_SPAN_LEVEL_WIDTH / pow(2, $zoom);
                $spanHeight = $this::ZOOM_SPAN_LEVEL_HEIGHT / pow(2, $zoom);
                if ($leftFrom > 0 && $leftTo < 0) {
                    $resultArray = $this->_calMapMission(array(
                        'leftFrom' => $leftFrom,
                        'leftTo' => 180,
                        'topEnd' => $topFrom,
                        'topStart' => $topTo,
                        'spanWidth' => $spanWidth,
                        'spanHeight' => $spanHeight,
                        'data' => $resultArray
                    ));
                    $resultArray = $this->_calMapMission(array(
                        'leftFrom' => -180,
                        'leftTo' => $leftTo,
                        'topEnd' => $topFrom,
                        'topStart' => $topTo,
                        'spanWidth' => $spanWidth,
                        'spanHeight' => $spanHeight,
                        'data' => $resultArray
                    ));
                } else {
                    $resultArray = $this->_calMapMission(array(
                        'leftFrom' => $leftFrom,
                        'leftTo' => $leftTo,
                        'topEnd' => $topFrom,
                        'topStart' => $topTo,
                        'spanWidth' => $spanWidth,
                        'spanHeight' => $spanHeight,
                        'data' => $resultArray
                    ));
                }
                $this->returnJSON($resultArray);
            }
        } else {
            $this->returnError("缺少参数");
        }

    }

    private function _calMapMission($paramArray)
    {

        $spanWidth = $paramArray['spanWidth'];
        $spanHeight = $paramArray['spanHeight'];
        $leftFrom = $paramArray['leftFrom'];
        $leftTo = $paramArray['leftTo'];
        $topStart = $paramArray['topStart'];
        $topEnd = $paramArray['topEnd'];
        $data = $paramArray['data'];

        $curLeft = $leftFrom;
        do {
            $curTop = $topStart;
            do {

                $targetLeftTo = $curLeft + $spanWidth;
                $targetTopTo = $curTop + $spanHeight;
                $sql = "select count(*) as total from flight_mission where home_lng>=$curLeft and home_lng<=$targetLeftTo and home_lat>=$curTop and home_lat<=$targetTopTo";
                $sqlData = $this->fetchOne($sql, 30);
                if ($sqlData['total'] > 0) {
                    $obj = array(
                        "total" => $sqlData['total'],
                        "leftFrom" => $curLeft,
                        "leftTo" => ($curLeft + $spanWidth),
                        "topFrom" => $curTop,
                        "topTo" => ($curTop + $spanHeight)
                    );

                    array_push($data, $obj);
                }
                $curTop += $spanHeight;
            } while ($curTop <= $topEnd);
            $curLeft += $spanWidth;
        } while ($curLeft <= $leftTo);
        return $data;
    }

    /**
     * 飞行监控统计
     */
    public function sysMapAction()
    {


        $this->view->setVars(array(
            'loginUser' => $this->getMonitorLoginUser(),
            'subsystems' => $this->getSubSystemInfo()
        ));
    }

    public function doSysMapDataAction(){
        $loginUser = $this->getMonitorLoginUser();
        
        $system_id = $this->request->get('system_id');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');
        $landingMethod = $this->request->get('landingMethod');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');
        
        $user = $this->request->get('user');
        $warrantyAt = $this->request->get('warrantyAt');
        
        $where = '';
        if ($landingMethod === '0') {
            $where .= " and f.landing_method = 0 ";
        }
        if ($landingMethod == '1') {
            $where .= " and f.landing_method <> 0 ";
        }
        
        if (!empty ($user)) {
            $where .= " and f.user_id = $user ";
        }
        if (!empty ($warrantyAt)) {
            $where .= " and p.warranty_at < '$warrantyAt' ";
        }
        if (!empty ($uas_serial_id)) {
//             $sql_user = "select id from user where nickname like '%$uas_serial_id%' or phone like '%$uas_serial_id%'";
//             $userids = $this->fetchAll($sql_user);
//             foreach ($userids as $user_id) {
//                 $user_id_arr [] = $user_id['id'];
//             }
//             if(count($user_id_arr)>0)
//                 $user_ids = implode(",", $user_id_arr);
//             else
//                 $user_ids = 0;
//             $where .= " and (u.uas_serial_id like '%$uas_serial_id%' or f.user_id in ($user_ids) ) ";
            $where .= " and (u.uas_serial_id like '%$uas_serial_id%' or f.survey_area_name  like '%$uas_serial_id%' or f.flight_task_name like '%$uas_serial_id%' ) ";
        }
        
        if (!empty ($startDate)) {
            $where .= " and u.created_at > '$startDate 00:00:00' ";
        }
        
        if (!empty ($endDate)) {
            $where .= " and u.created_at < '$endDate 23:59:59' ";
        }
        
        if (!empty ($planeModel)) {
            $where .= " and p.planeModel_id = $planeModel ";
        }
        
        if ($filterTime !== '0') {
            $filterTime = empty ($filterTime) ? 5 : $filterTime;
            $filterTime = $filterTime*60;
        }
        
        if ($filterDistance !== '0') {
            $filterDistance = empty ($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }
        
        $showSpace = empty ($showSpace) ? 'week' : $showSpace;
        $startDate = empty ($startDate) ? '' : $startDate;
        
        if (!empty ($system_id)) {
            $sql_system = "SELECT p.uas_serial_id FROM bind_plane_system as b,plane as p where b.plane_id=p.id and b.system_id =$system_id";
            $subSerialList = $this->fetchAll($sql_system);
            foreach ($subSerialList as $subSerial) {
                $subSerial_arr [] = $subSerial ['uas_serial_id'];
            }
            $subSerial_ids = implode("','", $subSerial_arr);
            if (!empty ($subSerial_ids)) {
                $where .= " and u.uas_serial_id in ('$subSerial_ids') ";
            } else {
                $where = " and u.uas_serial_id = 'noplane' ";
            }
        }
        
        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = " and f.user_id = " . $loginUser->userId;
        }
        
        $provinceSql = "select f.id as fmid,count(u.id) as uasid,u.uas_serial_id,
        (max(u.uas_odometer_value)-min(u.uas_odometer_value)) as odometer,
        max(u.stat_log_meter) as log_meter,
        p.planeModel_id,
        CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_meter)
        ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_meter)
        ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_meter),
        (max(u.uas_odometer_value)-min(u.uas_odometer_value))) END END as mil,
        CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_time)/3600
        ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_time)/3600
        ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_time)/3600,f.work_time/60) END END as work_time,
        max(u.stat_log_time) as time,
        f.work_area,f.home_lng as lng,f.home_lat as lat,u.created_at,f.survey_area_name,f.plane_type,f.flight_task_name,f.city,f.district,f.landing_method,
		p.expired_at,p.warranty_at,u.flight_sorties,u.uas_odometer_value 
        from flight_mission f,uas_status u,plane p
        where f.id=u.flight_mission_id and u.uas_serial_id=p.uas_serial_id and p.user_id<>7 and f.user_id not in (10,27,1699,1735) and (u.uas_serial_id like '%FF%' or u.uas_serial_id like '07JD%' or u.uas_serial_id like '11VK%')
        $where $user_type_where $user_where
        group by fmid HAVING (mil>$filterDistance or time>$filterTime) order by fmid";
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$provinceSql\r\n", FILE_APPEND);
        $uasRet = $this->fetchAll($provinceSql);
        
        $startTime = !empty ($startTime) ? strtotime($startTime) : '';
        $endTime = !empty ($endTime) ? strtotime($endTime . " 23:59:59") : '';        
        $chartData = $this->_createChartData($startTime, $endTime, $showSpace);
        
        $useTime = array();
        $itemMilAry = array();
        $planes = array();
        $missionList =  array();
        $mil = 0;
        $work_time = 0;
        $work_area = 0;
        
        $planeIdsSql = "select p.uas_serial_id,s.system_name from plane as p left join bind_plane_system as b on p.id=b.plane_id left join subsystem_info as s on b.system_id=s.id;";
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "plane sql:$planeIdsSql\r\n", FILE_APPEND);
        $planeRets = $this->fetchAll($planeIdsSql);
        $planeSystem = array();
        foreach ($planeRets as $planeRet) {
            $planeSystem[$planeRet['uas_serial_id']] = $planeRet['system_name'];
        }
        
        foreach ($uasRet as $uas) {
            $mil = $mil + $uas['mil'];
            $work_time = $work_time + $uas['work_time'];
            $work_area = $work_area + $uas['work_area'];
            $planes[$uas['uas_serial_id']]['uas_serial_id'] = $uas['uas_serial_id'];
            $planes[$uas['uas_serial_id']]['expired_at'] = $uas['expired_at'];
            $planes[$uas['uas_serial_id']]['planeModel_id'] = $uas['planeModel_id'];
            $planes[$uas['uas_serial_id']]['warranty_at'] = empty($uas['warranty_at']) ? "" : $uas['warranty_at'];
            $planes[$uas['uas_serial_id']]['flight_sorties'] = isset($planes[$uas['uas_serial_id']]['flight_sorties']) ? ($planes[$uas['uas_serial_id']]['flight_sorties'] + 1) : 1;
            $planes[$uas['uas_serial_id']]['uas_odometer_value'] = round(isset($planes[$uas['uas_serial_id']]['uas_odometer_value']) ? ($planes[$uas['uas_serial_id']]['uas_odometer_value'] + $uas['mil']) : $uas['mil']);
            if ($uas['landing_method'] === '0')
                $planes[$uas['uas_serial_id']]['landing_method'] = isset($planes[$uas['uas_serial_id']]['landing_method']) ? ($planes[$uas['uas_serial_id']]['landing_method'] + 1) : 1;
            else {
                $planes[$uas['uas_serial_id']]['landing_method'] = isset($planes[$uas['uas_serial_id']]['landing_method']) ? ($planes[$uas['uas_serial_id']]['landing_method'] + 0) : 0;
            }
            
            list ($dkey) = explode(' ', $uas['created_at']);
            if (!isset ($chartData [$dkey])) {
                continue;
            }
            
            if (!isset ($useTime [$chartData [$dkey]])) {
                $useTime [$chartData [$dkey]] = 0;
            }
            $useTime [$chartData [$dkey]] += 1;
            
            if (!isset ($itemMilAry [$chartData [$dkey]])) {
                $itemMilAry [$chartData [$dkey]] = 0;
            }
            $itemMilAry [$chartData [$dkey]] += $uas['mil'];
            
            $mission = array();
            $mission['id'] = $uas['fmid'];
            $mission['lng'] = $uas['lng'];
            $mission['lat'] = $uas['lat'];
            $mission['created_at'] = $uas['created_at'];
            $mission['survey_area_name'] = $uas['survey_area_name'];
            $mission['plane_type'] = $uas['plane_type'];
            $mission['flight_task_name'] = $uas['flight_task_name'];
            $mission['city'] = $uas['city'];
            $mission['district'] = $uas['district'];
            $mission['landing_method'] = $uas['landing_method'];
            $mission['uas_serial_id'] = $uas['uas_serial_id'];
            $mission['system_name'] = $planeSystem[$uas['uas_serial_id']];
            $missionList[] = $mission;
        }
        
//         foreach ($missionList as $key => $mission_list) {
//             $missionList[$key]['uas_serial_id'] = $ret ['planeSystem'][$mission_list['id']]['uas_serial_id'];
//             $missionList[$key]['system_name'] = $ret ['planeSystem'][$mission_list['id']]['system_name'];
//             $ret ['planeList'][$mission_list['id']]['landing_method'] = $mission_list['landing_method'];
//         }
        
        $chartDataTmp = array_values($chartData);
        $chartDataTmp = array_unique($chartDataTmp);
        $chartDataTmp = array_values($chartDataTmp);
        foreach ($chartDataTmp as $date) {
            if (!isset ($useTime [$date]))
                $useTime [$date] = 0;
                
            if (!isset ($itemMilAry [$date]))
                $itemMilAry [$date] = 0;
        }
        ksort($useTime);
        ksort($itemMilAry);
        
        $detail = array(
                'totalMission' => count($missionList),
                'totalMil' => $mil,
                'totalPlane' => count($planes)
        );
        
        $timeInterval = -2;
        $sql_onAir_fmid = 'SELECT m.* FROM (SELECT * FROM (SELECT m.id, u.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name, count(*) AS flight_count FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id WHERE NOT u.id IS NULL GROUP BY m.id) AS temp WHERE created_at >= date_add(now(), INTERVAL -2 HOUR) AND flight_count = 1)as m INNER JOIN (SELECT * from (SELECT * from uas_status WHERE created_at >= date_add(now(), INTERVAL -2 HOUR) AND is_takeoff=1 ORDER by created_at desc ) as temp GROUP by uas_serial_id) as uas on  m.id = uas.flight_mission_id';
        $uasOnAirFmidList = $this->fetchAll($sql_onAir_fmid);
        
        $uasTime1 = array_values($useTime);
        $itemMilAry1 = array_values($itemMilAry);
        $itemMilAry2 = array_sum($itemMilAry);
        
        $this->returnJson(array(
                'missionList' => json_encode($missionList),
                'planeList' => json_encode($planes),
                'fsTotal' => count($missionList),
                'detail' => $detail,
                'isGeted' => 0,
                'user' => $user,
                'uas_serial_id' => $uas_serial_id,
                'startDate' => $startDate,
                'endDate' => $endDate,
                'showSpace' => $showSpace,
                'planeModel' => $planeModel,
                'landingMethod' => $landingMethod,
                'warrantyAt' => $warrantyAt,
                'filterTime' => $filterTime/60,
                'filterDistance' => ($filterDistance * 1000),
                'currentFlyingList' => $uasOnAirFmidList,
                'currentFlyingCount' => count($uasOnAirFmidList),
                'chartDate' => json_encode($chartDataTmp),
                'useTime' => json_encode(array_values($useTime)),
                'milTimes' => json_encode(array_values($itemMilAry)),
                'milTotal' => $mil,
                'work_areas' => $work_area,
                'work_times' => $work_time
        ));
    }

    /**
     * 获取ajax查询数据
     */
    public function searchStatAction()
    {
        $loginUser = $this->getMonitorLoginUser();

        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and uas.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and uas.uas_serial_id = 'noplane' ";
            }
            
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and uas.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and uas.uas_serial_id = 'noplane' ";
            }
            
            $sql_user = "SELECT id FROM flight_mission where user_id =" . $loginUser->userId;
            $userMissionLists = $this->fetchAll($sql_user);
            foreach ($userMissionLists as $userMissionList) {
                $uas_mission_arr [] = $userMissionList['id'];
            }
            $uas_mission_ids = implode("','", $uas_mission_arr);
            if (!empty ($uas_mission_ids)) {
                $user_where = " and uas.flight_mission_id in ('$uas_mission_ids') ";
            }else{
                $user_where = " and uas.uas_serial_id = 'noplane' ";
            }
        }

        $system_id = $this->request->get('system_id');
        $user = $this->request->get('user');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');
        $landingMethod = $this->request->get('landingMethod');
        $warrantyAt = $this->request->get('warrantyAt');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');

        if ($filterTime !== '0') {
            $filterTime = empty ($filterTime) ? 5 : $filterTime;
        }
        if ($filterDistance !== '0') {
            $filterDistance = empty ($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }

        $showSpace = empty ($showSpace) ? 'week' : $showSpace;

        $isGeted = 0;

        if ($user || $uas_serial_id || $startDate || $endDate)
            $isGeted = 1;

        $startDate = empty ($startDate) ? '' : $startDate;

        $detail = array(
            'totalMission' => '',
            'totalMil' => '',
            'totalPlane' => ''
        );
        $ret = array(
            'chartDate' => '',
            'detail' => array(
                'useTime' => '',
                'milTimes' => ''
            )
        );

        $fmWhere = '';

        // if ($isGeted) {
        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id,planeModel_id,uas.stat_log_meter,uas.stat_log_time,plane.expired_at,plane.warranty_at
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ';

        $sql_serial = 'SELECT uas_serial_id FROM plane where user_id=7';
        $uasSerialList = $this->fetchAll($sql_serial);
        foreach ($uasSerialList as $uasSerial) {
            $uas_serial_arr [] = $uasSerial ['uas_serial_id'];
        }
        $uas_serial_ids = implode("','", $uas_serial_arr);
        if (!empty ($uas_serial_ids)) {
            $sql .= "and uas.uas_serial_id not in ('$uas_serial_ids') ";
        }

        if (!empty ($system_id)) {
            $sql_system = "SELECT p.uas_serial_id FROM bind_plane_system as b,plane as p where b.plane_id=p.id and b.system_id =$system_id";
            $subSerialList = $this->fetchAll($sql_system);
            foreach ($subSerialList as $subSerial) {
                $subSerial_arr [] = $subSerial ['uas_serial_id'];
            }
            $subSerial_ids = implode("','", $subSerial_arr);
            if (!empty ($subSerial_ids)) {
                $sql .= "and uas.uas_serial_id in ('$subSerial_ids') ";
            } else {
                $user_type_where = "and uas.uas_serial_id = 'noplane' ";
            }
        }

        if ($landingMethod === '0') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method = 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding ['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }
        if ($landingMethod == '1') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method <> 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding ['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }

        if ($warrantyAt === '0') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at<='" . date('Y-m-d') . "' and type<>0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty ['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }
        if ($warrantyAt == '1') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at>'" . date('Y-m-d') . "' or type=0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty ['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }

        $sql_fmid = 'select id from flight_mission where user_id in (10,27,1735,1699)';
        $uasFmidList = $this->fetchAll($sql_fmid);
        foreach ($uasFmidList as $uasFmid) {
            $uas_fmid_arr [] = $uasFmid ['id'];
        }
        $uas_fmid_ids = implode(',', $uas_fmid_arr);
        if (!empty ($uas_fmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_fmid_ids) ";
        }



        $sql_model = 'select id from plane_model';
        $planeModelList = $this->fetchAll($sql_model);
        foreach ($planeModelList as $planeModelId) {
            $plane_model_arr [] = $planeModelId ['id'];
        }
        $plane_model_ids = implode(',', $plane_model_arr);

        if (!empty ($where))
            // 过滤测试数据
            $sql .= ' where ' . $where . " and planeModel_id in ($plane_model_ids) " . $user_type_where . $user_where;
        else
            $sql .= " where planeModel_id in ($plane_model_ids) " . $user_type_where . $user_where;

        // $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= 'group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        // echo $sql;exit();
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count sql:$sql \r\n", FILE_APPEND);
        $uasList = $this->fetchAll($sql);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count uasList:" . count($uasList) . " \r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count startDate:$startDate, endDate:$endDate, showSpace:$showSpace, landingMethod:$landingMethod, warrantyAt:$warrantyAt, filterTime:$filterTime, filterDistance:$filterDistance, planeModel:$planeModel\r\n", FILE_APPEND);
        $ret = $this->_getStatDetail($uasList, $startDate, $endDate, $showSpace, $filterTime, $filterDistance);
        // file_put_contents ( "./log_" . date ( "Y-m-d" ) . ".txt", "\n" . date ( "H:i:s", time () ) . ':' . __METHOD__ . ':' . "ret ret_json:" . json_encode ( $ret ) . "\r\n", FILE_APPEND );
        $detail = array(
            'totalMission' => $ret ['totalMission'],
            'totalMil' => $ret ['totalMil'],
            'totalPlane' => $ret ['totalPlane']
        );

        if (!empty ($ret ['missionList'])) {
            $fmWhere = implode(',', $ret ['missionList']);
            $fmWhere = " where id in ($fmWhere)";
        }

        if (!empty ($isGeted) && empty ($fmWhere)) {
            $missionList = array();
        } else {
            if (empty ($fmWhere)) {
                $missionList = array();
            } else {
                $missionSql = "select id, home_lng as lng,home_lat as lat,created_at,survey_area_name,plane_type,flight_task_name,city,district,landing_method from flight_mission $fmWhere";
                file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "home sql:$missionSql\r\n", FILE_APPEND);
                $missionList = $this->fetchAll($missionSql);
            }
        }

        foreach ($missionList as $mission_list) {
            $ret ['planeList'] [$mission_list ['id']] ['landing_method'] = $mission_list ['landing_method'];
        }

        $planes = array();
        foreach ($ret ['planeList'] as $planeList) {
            $planes [$planeList ['uas_serial_id']] ['uas_serial_id'] = $planeList ['uas_serial_id'];
            $planes [$planeList ['uas_serial_id']] ['expired_at'] = $planeList ['expired_at'];
            $planes [$planeList ['uas_serial_id']] ['planeModel_id'] = $planeList ['planeModel_id'];
            $planes [$planeList ['uas_serial_id']] ['warranty_at'] = empty ($planeList ['warranty_at']) ? "" : $planeList ['warranty_at'];
            if ($planeList ['planeModel_id'] == 3) {
                $planes [$planeList ['uas_serial_id']] ['flight_sorties'] = isset ($planes [$planeList ['uas_serial_id']] ['flight_sorties']) ? ($planes [$planeList ['uas_serial_id']] ['flight_sorties'] + 1) : 1;
                $planes [$planeList ['uas_serial_id']] ['uas_odometer_value'] = round(isset ($planes [$planeList ['uas_serial_id']] ['uas_odometer_value']) ? ($planes [$planeList ['uas_serial_id']] ['uas_odometer_value'] + $planeList ['stat_log_meter']) : $planeList ['stat_log_meter']);
            } else {
                $planes [$planeList ['uas_serial_id']] ['flight_sorties'] = $planeList ['flight_sorties'];
                $planes [$planeList ['uas_serial_id']] ['uas_odometer_value'] = $planeList ['uas_odometer_value'];
            }
            if ($planeList ['landing_method'] === '0')
                $planes [$planeList ['uas_serial_id']] ['landing_method'] = isset ($planes [$planeList ['uas_serial_id']] ['landing_method']) ? ($planes [$planeList ['uas_serial_id']] ['landing_method'] + 1) : 1;
            else {
                $planes [$planeList ['uas_serial_id']] ['landing_method'] = isset ($planes [$planeList ['uas_serial_id']] ['landing_method']) ? ($planes [$planeList ['uas_serial_id']] ['landing_method'] + 0) : 0;
            }
        }

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "return json:" . json_encode($planes) . "\r\n", FILE_APPEND);
        if (empty ($ret))
            $this->returnError('暂无数据');
        $this->returnSuccess(array(
            'missionList' => json_encode($missionList),
            'useMissionList' => $ret ['missionList'],
            'planeLists' => $planes,
            'planeList' => json_encode($planes),
            'fsTotal' => $ret ['detail'] ['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'user' => $user,
            'uas_serial_id' => $uas_serial_id,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'showSpace' => $showSpace,
            'planeModel' => $planeModel,
            'landingMethod' => $landingMethod,
            'warrantyAt' => $warrantyAt,
            'filterTime' => $filterTime,
            'filterDistance' => ($filterDistance * 1000),
            'chartDate' => json_encode($ret ['chartDate']),
            'useTime' => json_encode($ret ['detail'] ['useTime']),
            'milTimes' => json_encode($ret ['detail'] ['milTimes']),
            'milTotal' => $ret ['detail'] ['milTotal'],
            'work_areas' => $ret ['detail'] ['workArea'],
            'work_times' => $ret ['detail'] ['workTime']
        ));
    }
    /**
     * 获取ajax查询数据
     */
    public function searchStatTempAction()
    {
//        $loginUser = $this->getMonitorLoginUser();

//        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
//            $user_type_where = "";
//            $user_where = '';
//        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
//            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
//            $subSystemList = $this->fetchAll($sql_subSystem);
//            foreach ($subSystemList as $subSystem) {
//                $subSystem_arr [] = $subSystem['uas_serial_id'];
//            }
//            $subSystem_ids = implode("','", $subSystem_arr);
//            if (!empty ($subSystem_ids)) {
//                $user_type_where = "and uas.uas_serial_id in ('$subSystem_ids') ";
//            } else {
//                $user_type_where = "and uas.uas_serial_id = 'noplane' ";
//            }
//
//            $user_where = '';
//        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
//        $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
//        $subSystemList = $this->fetchAll($sql_subSystem);
//        foreach ($subSystemList as $subSystem) {
//            $subSystem_arr [] = $subSystem['uas_serial_id'];
//        }
//        $subSystem_ids = implode("','", $subSystem_arr);
//        if (!empty ($subSystem_ids)) {
//            $user_type_where = "and uas.uas_serial_id in ('$subSystem_ids') ";
//        } else {
//            $user_type_where = "and uas.uas_serial_id = 'noplane' ";
//        }

//        $sql_user = "SELECT id FROM flight_mission where user_id =" . $loginUser->userId;
//        $userMissionLists = $this->fetchAll($sql_user);
//        foreach ($userMissionLists as $userMissionList) {
//            $uas_mission_arr [] = $userMissionList['id'];
//        }
//        $uas_mission_ids = implode("','", $uas_mission_arr);
//        if (!empty ($uas_mission_ids)) {
//            $user_where = " and uas.flight_mission_id in ('$uas_mission_ids') ";
//        }else{
//            $user_where = " and uas.uas_serial_id = 'noplane' ";
//        }
//    }

        $system_id = $this->request->get('system_id');
        $user = $this->request->get('user');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');
        $landingMethod = $this->request->get('landingMethod');
        $warrantyAt = $this->request->get('warrantyAt');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');

        if ($filterTime !== '0') {
            $filterTime = empty ($filterTime) ? 5 : $filterTime;
        }
        if ($filterDistance !== '0') {
            $filterDistance = empty ($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }

        $showSpace = empty ($showSpace) ? 'week' : $showSpace;

        $isGeted = 0;

        if ($user || $uas_serial_id || $startDate || $endDate)
            $isGeted = 1;

        $startDate = empty ($startDate) ? '' : $startDate;

        $detail = array(
            'totalMission' => '',
            'totalMil' => '',
            'totalPlane' => ''
        );
        $ret = array(
            'chartDate' => '',
            'detail' => array(
                'useTime' => '',
                'milTimes' => ''
            )
        );

        $fmWhere = '';

        // if ($isGeted) {
        $where = $this->_createWhere($user, $uas_serial_id, $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id,planeModel_id,uas.stat_log_meter,uas.stat_log_time,plane.expired_at,plane.warranty_at
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\') ';

        $sql_serial = 'SELECT uas_serial_id FROM plane where user_id=7';
        $uasSerialList = $this->fetchAll($sql_serial);
        foreach ($uasSerialList as $uasSerial) {
            $uas_serial_arr [] = $uasSerial ['uas_serial_id'];
        }
        $uas_serial_ids = implode("','", $uas_serial_arr);
        if (!empty ($uas_serial_ids)) {
            $sql .= "and uas.uas_serial_id not in ('$uas_serial_ids') ";
        }

        if (!empty ($system_id)) {
            $sql_system = "SELECT p.uas_serial_id FROM bind_plane_system as b,plane as p where b.plane_id=p.id and b.system_id =$system_id";
            $subSerialList = $this->fetchAll($sql_system);
            foreach ($subSerialList as $subSerial) {
                $subSerial_arr [] = $subSerial ['uas_serial_id'];
            }
            $subSerial_ids = implode("','", $subSerial_arr);
            if (!empty ($subSerial_ids)) {
                $sql .= "and uas.uas_serial_id in ('$subSerial_ids') ";
            } else {
                $user_type_where = "and uas.uas_serial_id = 'noplane' ";
            }
        }

        if ($landingMethod === '0') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method = 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding ['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }
        if ($landingMethod == '1') {
            $sql_landing = "SELECT id FROM flight_mission where landing_method <> 0";
            $uasLandingList = $this->fetchAll($sql_landing);
            foreach ($uasLandingList as $uasLanding) {
                $uas_landing_arr [] = $uasLanding ['id'];
            }
            $uas_landing_ids = implode("','", $uas_landing_arr);
            if (!empty ($uas_landing_ids)) {
                $sql .= "and uas.flight_mission_id in ('$uas_landing_ids') ";
            }
        }

        if ($warrantyAt === '0') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at<='" . date('Y-m-d') . "' and type<>0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty ['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }
        if ($warrantyAt == '1') {
            $sql_warranty = "SELECT uas_serial_id FROM plane where warranty_at>'" . date('Y-m-d') . "' or type=0";
            $uasWarrantyList = $this->fetchAll($sql_warranty);
            foreach ($uasWarrantyList as $uasWarranty) {
                $uas_warranty_arr [] = $uasWarranty ['uas_serial_id'];
            }
            $uas_warranty_ids = implode("','", $uas_warranty_arr);
            if (!empty ($uas_warranty_ids)) {
                $sql .= "and uas.uas_serial_id in ('$uas_warranty_ids') ";
            }
        }

        $sql_fmid = 'select id from flight_mission where user_id in (10,27,1735,1699)';
        $uasFmidList = $this->fetchAll($sql_fmid);
        foreach ($uasFmidList as $uasFmid) {
            $uas_fmid_arr [] = $uasFmid ['id'];
        }
        $uas_fmid_ids = implode(',', $uas_fmid_arr);
        if (!empty ($uas_fmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_fmid_ids) ";
        }



        $sql_model = 'select id from plane_model';
        $planeModelList = $this->fetchAll($sql_model);
        foreach ($planeModelList as $planeModelId) {
            $plane_model_arr [] = $planeModelId ['id'];
        }
        $plane_model_ids = implode(',', $plane_model_arr);

        if (!empty ($where))
            // 过滤测试数据
            $sql .= ' where ' . $where . " and planeModel_id in ($plane_model_ids) " . $user_type_where . $user_where;
        else
            $sql .= " where planeModel_id in ($plane_model_ids) " . $user_type_where . $user_where;

        // $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= 'group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        // echo $sql;exit();
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count sql:$sql \r\n", FILE_APPEND);
        $uasList = $this->fetchAll($sql);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count uasList:" . count($uasList) . " \r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count startDate:$startDate, endDate:$endDate, showSpace:$showSpace, landingMethod:$landingMethod, warrantyAt:$warrantyAt, filterTime:$filterTime, filterDistance:$filterDistance, planeModel:$planeModel\r\n", FILE_APPEND);
        $ret = $this->_getStatDetail($uasList, $startDate, $endDate, $showSpace, $filterTime, $filterDistance);
        // file_put_contents ( "./log_" . date ( "Y-m-d" ) . ".txt", "\n" . date ( "H:i:s", time () ) . ':' . __METHOD__ . ':' . "ret ret_json:" . json_encode ( $ret ) . "\r\n", FILE_APPEND );
        $detail = array(
            'totalMission' => $ret ['totalMission'],
            'totalMil' => $ret ['totalMil'],
            'totalPlane' => $ret ['totalPlane']
        );

        if (!empty ($ret ['missionList'])) {
            $fmWhere = implode(',', $ret ['missionList']);
            $fmWhere = " where id in ($fmWhere)";
        }

        if (!empty ($isGeted) && empty ($fmWhere)) {
            $missionList = array();
        } else {
            if (empty ($fmWhere)) {
                $missionList = array();
            } else {
                $missionSql = "select id, home_lng as lng,home_lat as lat,created_at,survey_area_name,plane_type,flight_task_name,city,district,landing_method from flight_mission $fmWhere";
                file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "home sql:$missionSql\r\n", FILE_APPEND);
                $missionList = $this->fetchAll($missionSql);
            }
        }

        foreach ($missionList as $mission_list) {
            $ret ['planeList'] [$mission_list ['id']] ['landing_method'] = $mission_list ['landing_method'];
        }

        $planes = array();
        foreach ($ret ['planeList'] as $planeList) {
            $planes [$planeList ['uas_serial_id']] ['uas_serial_id'] = $planeList ['uas_serial_id'];
            $planes [$planeList ['uas_serial_id']] ['expired_at'] = $planeList ['expired_at'];
            $planes [$planeList ['uas_serial_id']] ['planeModel_id'] = $planeList ['planeModel_id'];
            $planes [$planeList ['uas_serial_id']] ['warranty_at'] = empty ($planeList ['warranty_at']) ? "" : $planeList ['warranty_at'];
            if ($planeList ['planeModel_id'] == 3 || $planeList ['planeModel_id'] == 8) {
                $planes [$planeList ['uas_serial_id']] ['flight_sorties'] = isset ($planes [$planeList ['uas_serial_id']] ['flight_sorties']) ? ($planes [$planeList ['uas_serial_id']] ['flight_sorties'] + 1) : 1;
                $planes [$planeList ['uas_serial_id']] ['uas_odometer_value'] = round(isset ($planes [$planeList ['uas_serial_id']] ['uas_odometer_value']) ? ($planes [$planeList ['uas_serial_id']] ['uas_odometer_value'] + $planeList ['stat_log_meter']) : $planeList ['stat_log_meter']);
            } else {
                $planes [$planeList ['uas_serial_id']] ['flight_sorties'] = $planeList ['flight_sorties'];
                $planes [$planeList ['uas_serial_id']] ['uas_odometer_value'] = $planeList ['uas_odometer_value'];
            }
            if ($planeList ['landing_method'] === '0')
                $planes [$planeList ['uas_serial_id']] ['landing_method'] = isset ($planes [$planeList ['uas_serial_id']] ['landing_method']) ? ($planes [$planeList ['uas_serial_id']] ['landing_method'] + 1) : 1;
            else {
                $planes [$planeList ['uas_serial_id']] ['landing_method'] = isset ($planes [$planeList ['uas_serial_id']] ['landing_method']) ? ($planes [$planeList ['uas_serial_id']] ['landing_method'] + 0) : 0;
            }
        }

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "return json:" . json_encode($planes) . "\r\n", FILE_APPEND);
        if (empty ($ret))
            $this->returnError('暂无数据');
        $this->returnSuccess(array(
            'missionList' => json_encode($missionList),
            'useMissionList' => $ret ['missionList'],
            'planeLists' => $planes,
            'planeList' => json_encode($planes),
            'fsTotal' => $ret ['detail'] ['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'user' => $user,
            'uas_serial_id' => $uas_serial_id,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'showSpace' => $showSpace,
            'planeModel' => $planeModel,
            'landingMethod' => $landingMethod,
            'warrantyAt' => $warrantyAt,
            'filterTime' => $filterTime,
            'filterDistance' => ($filterDistance * 1000),
            'chartDate' => json_encode($ret ['chartDate']),
            'useTime' => json_encode($ret ['detail'] ['useTime']),
            'milTimes' => json_encode($ret ['detail'] ['milTimes']),
            'milTotal' => $ret ['detail'] ['milTotal'],
            'work_areas' => $ret ['detail'] ['workArea'],
            'work_times' => $ret ['detail'] ['workTime']
        ));
    }

    /**
     * 废弃,请不要使用
     * 请求实时架次信息
     */
    public function requestFlyingTaskCountAction()
    {
        $token=$this->request->get('token');
        if(empty($token)){
            $this->returnError("token错误");
        }
        //时间间隔
        $timeInterval=-2;

        $sql = "

select *,flight_task.local_id as task_local_id from (
SELECT m.*
FROM (SELECT *
      FROM (SELECT
              m.id,
              m.user_id,
              m.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name,flight_task_id,
                           count(*) AS flight_count
            FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id
            WHERE NOT u.id IS NULL
            GROUP BY m.id) AS temp
            WHERE
       created_at >= date_add(now(), INTERVAL $timeInterval HOUR) AND flight_count = 1
          AND user_id = (select id from user where token = '$token')

)as m
  INNER JOIN (
   SELECT * from (

    SELECT * from uas_status WHERE created_at >= date_add(now(), INTERVAL $timeInterval HOUR) AND is_takeoff=1 ORDER by created_at desc ) as temp

    GROUP by uas_serial_id


  ) as u on  m.id = u.flight_mission_id) as u 
  
  LEFT JOIN flight_task on  u.flight_task_id=flight_task.local_id
  ";

        $data = $this->fetchAll($sql);
        $this->returnJson($data);
    }


    /**
     * 请求实时架次信息
     */
    public function requestFlightingCountAction()
    {
        $loginUser = $this->getMonitorLoginUser();
        $subsytemId=$this->getQuery("subsystem_id");
        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            if($subsytemId){
                $user_type_where=$this->_getUserTypeWhere($subsytemId);
            }
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $user_type_where=$this->_getUserTypeWhere($loginUser->subsystemId);
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $user_type_where=$this->_getUserTypeWhere($loginUser->subsystemId);
            
            $sql_user = "SELECT id FROM flight_mission where user_id =" . $loginUser->userId;
            $userMissionLists = $this->fetchAll($sql_user);
            foreach ($userMissionLists as $userMissionList) {
                $uas_mission_arr [] = $userMissionList['id'];
            }
            $uas_mission_ids = implode("','", $uas_mission_arr);
            if (!empty ($uas_mission_ids)) {
                $user_where = " and u.flight_mission_id in ('$uas_mission_ids') ";
            }else{
                $user_where = " and u.uas_serial_id = 'noplane' ";
            }
        }

        // 时间间隔
        $timeInterval = -2;

        $sql = "SELECT m.*
        FROM (SELECT *
        FROM (SELECT
        m.id,m.local_id,
        u.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name,
        count(*) AS flight_count
        FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id
        WHERE NOT u.id IS NULL 
        GROUP BY m.id) AS temp
        WHERE created_at >= date_add(now(), INTERVAL $timeInterval HOUR) AND flight_count = 1
        
        )as m
        INNER JOIN (
        SELECT * from (
        
        SELECT * from uas_status WHERE created_at >= date_add(now(), INTERVAL $timeInterval HOUR) AND is_takeoff=1 ORDER by created_at desc ) as temp
        
        GROUP by uas_serial_id
            
        ) as u on  m.id = u.flight_mission_id where 1 $user_type_where".$user_where;


        // where 1 ' . $user_type_where
//        header('Content-type: application/json');
//        header('Access-Control-Allow-Origin:*');
        $data = $this->fetchAll($sql);
        $records =  array();
        
        foreach($data as $onAir){
            if(!empty($onAir['local_id'])&&$this->redis->exists('detail-upload-fmid-'.$onAir['local_id'])){
                unset($onAir['local_id']);
                $records[]= $onAir;
            }
        }
        
        $this->returnJson($records);
    }

    private function _getUserTypeWhere($subSystemId){
        $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $subSystemId;
        $subSystemList = $this->fetchAll($sql_subSystem);
        foreach ($subSystemList as $subSystem) {
            $subSystem_arr [] = $subSystem['uas_serial_id'];
        }
        $subSystem_ids = implode("','", $subSystem_arr);
        if (!empty ($subSystem_ids)) {
            $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
        } else {
            $user_type_where = "and u.uas_serial_id = 'noplane' ";
        }
        return $user_type_where;



    }

    /**
     * 获取任务信息数据
     */
    public function missionInfoAction()
    {
        $id = $this->getPost('id');
        $id = intval($id);

        if (empty ($id))
            $this->returnError('id不能为空');

        $sql = "select fm.id,fm.camera_type,us.uas_odometer_value,fm.average_ground_resolution,fm.high_longitudinal_overlap,fm.high_lateral_overlap,
            fm.flight_interval,fm.take_pic_interval,fm.work_area,fm.work_time,fm.flight_relative_altitude,fm.flight_altitude,fm.default_air_speed,
            fm.landing_method,us.is_takeoff,fm.task_coordinate_waypoints ,fm.home_lng,fm.home_lat,fm.flight_task_name,us.uas_serial_id,us.created_at,fm.user_id, plane_model.name as model
            from flight_mission as fm
            left join uas_status as us
            on fm.id = us.flight_mission_id
            left join plane on us.uas_serial_id = plane.uas_serial_id
            left join plane_model on plane.planeModel_id = plane_model.id
            where fm.id = $id group by us.is_takeoff";

        $info = $this->fetchAll($sql);
        if (empty ($info))
            $this->returnError("mission信息为空");

        $sOdometer = 0;
        $eOdometer = 0;
        $mission = [];
        $uas_serial_id = 0;
        $stime = '';
        $etime = '';
        foreach ($info as $key => $val) {
            if ($val ['is_takeoff'] == '1') {
                $stime = date('H:i', strtotime($val ['created_at']));
                $sOdometer = $val ['uas_odometer_value'];
            } else {
                $eOdometer = $val ['uas_odometer_value'];
                $etime = date('H:i', strtotime($val ['created_at']));
                $mission = $val;
            }
        }

        $sql = "select company from user where id={$mission['user_id']}";
        $company = $this->fetchOne($sql) ['company'];

        $mission ['work_mil'] = $eOdometer - $sOdometer;
        $mission ['company'] = $company;
        $mission ['flightTime'] = "$stime-$etime";
        $mission ['created_at'] = date('Y-m-d', strtotime($mission ['created_at']));

        $this->returnSuccess($mission);
    }

    /**
     * 获取block详细信息
     */
    public function requestBlockDetailAction()
    {
        $missionId = $this->request->get('id');
        $sql = "select * from flight_mission WHERE id=$missionId";

        $data = $this->fetchOne($sql);
        $PlaneSql = "SELECT temp.uas_serial_id,plane.phone from (
        SELECT uas_serial_id from uas_status WHERE flight_mission_id=$missionId
        and uas_serial_id is NOT null
        GROUP by uas_serial_id
        ) as temp  left JOIN plane on plane.uas_serial_id=temp.uas_serial_id
        ";
        $planeInfoData = $this->fetchOne($PlaneSql);
        $cs=$this->isProjectUseWgs84ByLocalId($data["project_id"]);
        if($cs){
            $cs="wgs84";
        }else{
            $cs="gcj02";
        }
        if($data&($data["plane_type"]=="D1000"||
            $data["plane_type"]=="Phantom 4 Pro"||
            $data["plane_type"]=="Inspire 2")
        ){
            $cs="gcj02";

        }
        $this->returnJson(array(
            'block_info' => $data,
            'plane_info' => $planeInfoData,
            'cs'=>$cs
        ));
    }

    /******************************   统计相关    ***********************************************************/

    public function sysStatAction()
    {
        $user=$this->getMonitorLoginUser();

        $this->view->setVars(array(
            "systemLists"=>$this->getSubSystemInfo(),
            "planeModelList"=>$this->getPlaneModelInfo(),
            "subsystemId"=>$user->subsystemId,
            "cameraType"=>$this->getCameraType()
        ));
    }
    
    public function sysStatSearchAction()
    {
        $loginUser = $this->getMonitorLoginUser();
        
        $system_id = $this->request->get('system_id');
        $uas_serial_id = $this->request->get('uas_serial_id');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $cameraType = $this->request->get('camera_type');
        $planeModel = $this->request->get('planeModel');
        $landingMethod = $this->request->get('landingMethod');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');
        
        $where = '';
        if ($landingMethod === '0') {
            $where .= " and f.landing_method = 0 ";
        }
        if ($landingMethod == '1') {
                $where .= " and f.landing_method <> 0 ";
        }
        
        if (!empty ($uas_serial_id)) {
            $where .= " and u.uas_serial_id like '%$uas_serial_id%' ";
        }
        
        if (!empty ($startDate)) {
            $where .= " and u.created_at > '$startDate 00:00:00' ";
        }
        
        if (!empty ($endDate)) {
            $where .= " and u.created_at < '$endDate 23:59:59' ";
        }
        
        if (!empty ($planeModel)) {
            $where .= " and p.planeModel_id = $planeModel ";
        }
        
        if (!empty ($cameraType)) {
            if ($cameraType == "NONE"){
                $where .= " and f.camera_type = '' ";
            } else{
                $where .= " and f.camera_type = '$cameraType' ";
            }
        }
        
        if ($filterTime !== '0') {
            $filterTime = empty ($filterTime) ? 5 : $filterTime;
            $filterTime = $filterTime*60;
        }
        
        if ($filterDistance !== '0') {
            $filterDistance = empty ($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }
        
        if (!empty ($system_id)) {
            $sql_system = "SELECT p.uas_serial_id FROM bind_plane_system as b,plane as p where b.plane_id=p.id and b.system_id =$system_id";
            $subSerialList = $this->fetchAll($sql_system);
            foreach ($subSerialList as $subSerial) {
                $subSerial_arr [] = $subSerial ['uas_serial_id'];
            }
            $subSerial_ids = implode("','", $subSerial_arr);
            if (!empty ($subSerial_ids)) {
                $where .= " and u.uas_serial_id in ('$subSerial_ids') ";
            } else {
                $where = " and u.uas_serial_id = 'noplane' ";
            }
        }        
        
        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = " and f.user_id = " . $loginUser->userId;
        }
        
        $provinceSql = "select 
sum(mil) as mil,sum(work_time) as work_time,sum(fmid) as fmid,sum(work_area) as work_area,province,count(uas_serial_id) as uas_serial_id
from (select 
sum(mil) as mil,sum(work_time) as work_time,count(fmid) as fmid,sum(work_area) as work_area,province,uas_serial_id
from (select f.id as fmid,count(u.id) as uasid,u.uas_serial_id,
(max(u.uas_odometer_value)-min(u.uas_odometer_value)) as odometer,
max(u.stat_log_meter) as log_meter,
p.planeModel_id,
CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_meter)
			ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_meter)
			ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_meter),
(max(u.uas_odometer_value)-min(u.uas_odometer_value))) END END as mil,
CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_time)/3600
			ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_time)/3600
			ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_time)/3600,f.work_time/60) END END as work_time,
max(u.stat_log_time) as time,
f.work_area,u.province
from flight_mission f,uas_status u,plane p 
where f.id=u.flight_mission_id and u.uas_serial_id=p.uas_serial_id and p.user_id<>7 and f.user_id not in (10,27,1699,1735) and (u.uas_serial_id like '%FF%' or u.uas_serial_id like '07JD%' or u.uas_serial_id like '11VK%') 
$where $user_type_where $user_where 
group by fmid HAVING (mil>$filterDistance or time>$filterTime) order by fmid) as temp GROUP BY province,uas_serial_id) as temp2 GROUP BY province";
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$provinceSql\r\n", FILE_APPEND);
        $provinceRet = $this->fetchAll($provinceSql);
        
        
        
        $missionProvince = array();
        $workTime = 0;
        $workArea = 0;
        $totalMil = 0;
        $totalMission = 0;
        foreach ($provinceRet as $province) {
            if(is_null($province['province'])){
                $missionProvince['null']['workTime']=$province['work_time'];
                $missionProvince['null']['work_areas']=$province['work_area'];
                $missionProvince['null']['sumMil']=$province['mil'];
                $missionProvince['null']['fsTotal']=$province['fmid'];
                $missionProvince['null']['planes']=$province['uas_serial_id'];
            }else{
                $missionProvince[$province['province']]['workTime']=$province['work_time'];
                $missionProvince[$province['province']]['work_areas']=$province['work_area'];
                $missionProvince[$province['province']]['sumMil']=$province['mil'];
                $missionProvince[$province['province']]['fsTotal']=$province['fmid'];
                $missionProvince[$province['province']]['planes']=$province['uas_serial_id'];
            }
            $workTime = $workTime+$province['work_time'];
            $workArea = $workArea+$province['work_area'];
            $totalMil = $totalMil+$province['mil'];
            $totalMission = $totalMission+$province['fmid'];
        }
        
        $planeSql = "select DISTINCT uas_serial_id
from (select f.id as fmid,count(u.id) as uasid,u.uas_serial_id,
(max(u.uas_odometer_value)-min(u.uas_odometer_value)) as odometer,
max(u.stat_log_meter) as log_meter,
p.planeModel_id,
CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_meter)
			ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_meter)
			ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_meter),
(max(u.uas_odometer_value)-min(u.uas_odometer_value))) END END as mil,
CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_time)/3600
			ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_time)/3600
			ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_time)/3600,f.work_time/60) END END as work_time,
max(u.stat_log_time) as time,
f.work_area,u.province
from flight_mission f,uas_status u,plane p 
where f.id=u.flight_mission_id and u.uas_serial_id=p.uas_serial_id and p.user_id<>7 and f.user_id not in (10,27,1699,1735) and (u.uas_serial_id like '%FF%' or u.uas_serial_id like '07JD%' or u.uas_serial_id like '11VK%') 
$where $user_type_where $user_where 
group by fmid HAVING (mil>$filterDistance or time>$filterTime) order by fmid) as temp";
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$planeSql\r\n", FILE_APPEND);
        $planes = $this->fetchAll($planeSql);
        
        
        $this->returnSuccess(array(
                'totalPlane' => count($planes),
                'totalMil' => round($totalMil,2),
                'work_areas' => round($workArea,2),
                'work_times' => round($workTime,2),
                'totalMission' => $totalMission,
                'statDate' => date('Y-m-d H:i'),
                'provinceList' => json_encode ( $missionProvince )
        ) );
    }
    
    public function sysCompareStatAction()
    {
         $user=$this->getMonitorLoginUser();

        //获取飞机类型
        $planeModels = $this->getPlaneModelInfo();
        $this->view->setVars(array(
            "planeModels" => $planeModels,
            "planeModelsStr"=>json_encode($planeModels)
        ));
    }


    /**
     * 获取某点坐标高程
     */
    public function ajaxHomeElevationAction()
    {
        $lat_lng = $this->request->getPost('lat_lng');

        if (empty($lat_lng) || !is_array($lat_lng))
            $this->returnError('初始化人物点失败');

        $lat_lng = "{$lat_lng[1]},{$lat_lng[0]}";

        $url = 'http://115.159.44.126:8081/bing/getelevationbypoint';

        exit($this->curlRequest($url, 'GET', array(
            'lat_lng' => $lat_lng
        )));
    }

    /**
     * 对比统计
     */
    public function sysLineAction()
    {
        $loginUser = $this->getMonitorLoginUser();
        
        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and uas.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and uas.uas_serial_id = 'noplane' ";
            }
            
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and uas.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and uas.uas_serial_id = 'noplane' ";
            }
            
            $sql_user = "SELECT id FROM flight_mission where user_id =" . $loginUser->userId;
            $userMissionLists = $this->fetchAll($sql_user);
            foreach ($userMissionLists as $userMissionList) {
                $uas_mission_arr [] = $userMissionList['id'];
            }
            $uas_mission_ids = implode("','", $uas_mission_arr);
            if (!empty ($uas_mission_ids)) {
                $user_where = " and uas.flight_mission_id in ('$uas_mission_ids') ";
            }else{
                $user_where = " and uas.uas_serial_id = 'noplane' ";
            }
        }

        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');

        if ($filterTime !== '0') {
            $filterTime = empty ($filterTime) ? 5 : $filterTime;
        }
        if ($filterDistance !== '0') {
            $filterDistance = empty ($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }

        $showSpace = empty ($showSpace) ? 'week' : $showSpace;

        $isGeted = 0;

        if ($startDate || $endDate)
            $isGeted = 1;

        $startDate = empty ($startDate) ? '' : $startDate;

        $detail = array(
            'totalMission' => '',
            'totalMil' => '',
            'totalPlane' => ''
        );
        $ret = array(
            'chartDate' => '',
            'detail' => array(
                'useTime' => '',
                'milTimes' => ''
            )
        );

        $fmWhere = '';

        // if ($isGeted) {
        $where = $this->_createWhere('', '', $startDate, $endDate, 'uas', $planeModel);
        $sql = 'select uas.id,uas.flight_sorties,uas.uas_odometer_value,uas.opening_parachute_times,uas.uas_serial_id,uas.is_takeoff,uas.created_at,uas.flight_mission_id,planeModel_id,uas.stat_log_meter,uas.stat_log_time,plane.expired_at,plane.warranty_at
                from uas_status as uas left join plane on uas.uas_serial_id = plane.uas_serial_id and (uas.uas_serial_id like \'%FF%\' or uas.uas_serial_id like \'07JD%\' or uas.uas_serial_id like \'11VK%\') ';

        $sql_serial = 'SELECT uas_serial_id FROM plane where user_id=7';
        $uasSerialList = $this->fetchAll($sql_serial);
        foreach ($uasSerialList as $uasSerial) {
            $uas_serial_arr [] = $uasSerial ['uas_serial_id'];
        }
        $uas_serial_ids = implode("','", $uas_serial_arr);
        if (!empty ($uas_serial_ids)) {
            $sql .= "and uas.uas_serial_id not in ('$uas_serial_ids') ";
        }

        $sql_fmid = 'select id from flight_mission where user_id in (10,27,1735,1699)';
        $uasFmidList = $this->fetchAll($sql_fmid);
        foreach ($uasFmidList as $uasFmid) {
            $uas_fmid_arr [] = $uasFmid ['id'];
        }
        $uas_fmid_ids = implode(',', $uas_fmid_arr);
        if (!empty ($uas_fmid_ids)) {
            $sql .= "and uas.flight_mission_id not in($uas_fmid_ids) ";
        }

        $timeInterval = -2;
        $sql_onAir_fmid = 'SELECT m.* FROM (SELECT * FROM (SELECT m.id, u.created_at,m.home_lng as lng,m.home_lat as lat,m.survey_area_name, count(*) AS flight_count FROM flight_mission AS m LEFT JOIN uas_status AS u ON m.id = u.flight_mission_id WHERE NOT u.id IS NULL GROUP BY m.id) AS temp WHERE created_at >= date_add(now(), INTERVAL -2 HOUR) AND flight_count = 1)as m INNER JOIN (SELECT * from (SELECT * from uas_status WHERE created_at >= date_add(now(), INTERVAL -2 HOUR) AND is_takeoff=1 ORDER by created_at desc ) as temp GROUP by uas_serial_id) as uas on  m.id = uas.flight_mission_id';
        $uasOnAirFmidList = $this->fetchAll($sql_onAir_fmid);
        foreach ($uasOnAirFmidList as $uasOnAirFmid) {
            if (in_array($uasOnAirFmid ['id'], $uas_fmid_arr)) {
                $flag = $uasOnAirFmid ['id'];
            }
            $uas_OnAirfmid_arr [] = $uasOnAirFmid ['id'];
        }
        if (!empty($uas_OnAirfmid_arr)) {
            $uas_OnAirfmid_ids = implode(',', $uas_OnAirfmid_arr);
            if (!empty ($uas_OnAirfmid_ids)) {
                $sql .= "and uas.flight_mission_id not in($uas_OnAirfmid_ids) ";
            }
        }

        $sql_model = 'select id from plane_model';
        $planeModelList = $this->fetchAll($sql_model);
        foreach ($planeModelList as $planeModelId) {
            $plane_model_arr [] = $planeModelId ['id'];
        }
        $plane_model_ids = implode(',', $plane_model_arr);

        if (!empty ($where))
            // 过滤测试数据
            $sql .= ' where ' . $where . " and planeModel_id in ($plane_model_ids) " . $user_type_where . $user_where;
        else
            $sql .= " where planeModel_id in ($plane_model_ids) " . $user_type_where . $user_where;

        // $sql .=' group by uas.flight_mission_id , is_takeoff';
        $sql .= 'group by uas.flight_mission_id , uas.is_takeoff order by uas.flight_mission_id asc, uas.id asc';

        // echo $sql;exit();
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count sql:$sql \r\n", FILE_APPEND);
        $uasList = $this->fetchAll($sql);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count uasList:" . count($uasList) . " \r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "count startDate:$startDate, endDate:$endDate, showSpace:$showSpace, filterTime:$filterTime, filterDistance:$filterDistance, planeModel:$planeModel\r\n", FILE_APPEND);
        $ret = $this->_getStatLine($uasList, $startDate, $endDate, $showSpace, $filterTime, $filterDistance);
        // file_put_contents ( "./log_" . date ( "Y-m-d" ) . ".txt", "\n" . date ( "H:i:s", time () ) . ':' . __METHOD__ . ':' . "ret ret_json:" . json_encode ( $ret ) . "\r\n", FILE_APPEND );
        $detail = array(
            'totalMission' => $ret ['totalMission'],
            'totalMil' => $ret ['totalMil'],
            'totalPlane' => $ret ['totalPlane']
        );

        $allUseTime = $ret ['detail'] ['allUseTime'];
        $allMilTimes = $ret ['detail'] ['allMilTimes'];
        $planeModels = array();
        foreach ($ret ['detail'] ['allUseTime'] as $key => $value) {
            if (!empty($key)) {
                $planeModels[] = $key;
            }
        }

        $this->view->setVars(array(
            'fsTotal' => $ret ['detail'] ['fsTotal'],
            'detail' => $detail,
            'isGeted' => $isGeted,
            'startDate' => $startDate,
            'endDate' => $endDate,
            'showSpace' => $showSpace,
            'planeModel' => $planeModel,
            'filterTime' => $filterTime,
            'filterDistance' => ($filterDistance * 1000),
            'planeModels' => $planeModels,
            'chartDate' => json_encode($ret ['chartDate']),
            'useTime' => json_encode($ret ['detail'] ['useTime']),
            'milTimes' => json_encode($ret ['detail'] ['milTimes']),
            'allUseTime' => json_encode($allUseTime),
            'allMilTimes' => json_encode($allMilTimes),
            'milTotal' => $ret ['detail'] ['milTotal']
        ));
    }

    /**
     * 对比统计
     */
    public function searchSysLineAction()
    {
        $loginUser = $this->getMonitorLoginUser();
        
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $showSpace = $this->request->get('showSpace');
        $planeModel = $this->request->get('planeModel');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');
        
        $where = '';
        
        if (!empty ($startDate)) {
            $where .= " and u.created_at > '$startDate 00:00:00' ";
        }
        
        if (!empty ($endDate)) {
            $where .= " and u.created_at < '$endDate 23:59:59' ";
        }
        
        if (!empty ($planeModel)) {
            $where .= " and p.planeModel_id = $planeModel ";
        }
        
        if ($filterTime !== '0') {
            $filterTime = empty ($filterTime) ? 5 : $filterTime;
            $filterTime = $filterTime*60;
        }
        
        if ($filterDistance !== '0') {
            $filterDistance = empty ($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }
        
        $showSpace = empty ($showSpace) ? 'week' : $showSpace;
        $startDate = empty ($startDate) ? '' : $startDate;
        
        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = " and f.user_id = " . $loginUser->userId;
        }
        
        $provinceSql = "select f.id as fmid,count(u.id) as uasid,u.uas_serial_id,p.planeModel_id,
        CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_meter)
        ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_meter)
        ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_meter),
        (max(u.uas_odometer_value)-min(u.uas_odometer_value))) END END as mil,
        max(u.stat_log_time) as time,u.created_at 
        from flight_mission f,uas_status u,plane p
        where f.id=u.flight_mission_id and u.uas_serial_id=p.uas_serial_id and p.user_id<>7 and f.user_id not in (10,27,1699,1735) and (u.uas_serial_id like '%FF%' or u.uas_serial_id like '07JD%' or u.uas_serial_id like '11VK%')
        $where $user_type_where $user_where
        group by fmid HAVING (mil>$filterDistance or time>$filterTime) order by fmid";
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$provinceSql\r\n", FILE_APPEND);
        $uasRet = $this->fetchAll($provinceSql);
        
        $startTime = !empty ($startTime) ? strtotime($startTime) : '';
        $endTime = !empty ($endTime) ? strtotime($endTime . " 23:59:59") : '';
        $chartData = $this->_createChartData($startTime, $endTime, $showSpace);
        
        $useTime = array();
        $itemMilAry = array();
        $planes = array();
        $mil = 0;
        
        foreach ($uasRet as $uas) {
            $planes[$uas['uas_serial_id']] = $uas['uas_serial_id'];
            $mil = $mil + $uas['mil'];               
                
            list ($dkey) = explode(' ', $uas ['created_at']);
            if (!isset ($chartData [$dkey])) {
                continue;
            }
            
            if (!isset ($useTime['0'] [$chartData [$dkey]])) {
                $useTime['0'] [$chartData [$dkey]] = 0;
            }
            $useTime['0'] [$chartData [$dkey]] += 1;
            
            if (!isset ($useTime[$uas['planeModel_id']] [$chartData [$dkey]])) {
                $useTime[$uas['planeModel_id']] [$chartData [$dkey]] = 0;
            }
            $useTime[$uas['planeModel_id']] [$chartData [$dkey]] += 1;
            
            if (!isset ($itemMilAry['0'] [$chartData [$dkey]])) {
                $itemMilAry['0'][$chartData [$dkey]] = 0;
            }
            $itemMilAry['0'][$chartData [$dkey]] += $uas['mil'];
            
            if (!isset ($itemMilAry[$uas['planeModel_id']] [$chartData [$dkey]])) {
                $itemMilAry[$uas['planeModel_id']][$chartData [$dkey]] = 0;
            }
            $itemMilAry[$uas['planeModel_id']][$chartData [$dkey]] += $uas['mil'];
        }
        
        $chartDataTmp = array_values($chartData);
        $chartDataTmp = array_unique($chartDataTmp);
        $chartDataTmp = array_values($chartDataTmp);
        foreach ($chartDataTmp as $date) {
            foreach ($useTime as $key => $value) {
                if (!isset ($useTime[$key][$date])) {
                    $useTime[$key][$date] = 0;
                }
                if (!isset ($itemMilAry[$key][$date])) {
                    $itemMilAry[$key][$date] = 0;
                }
            }
        }
        
        foreach ($useTime as $key => $value) {
            ksort($useTime[$key]);
            ksort($itemMilAry[$key]);
        }
        
        $uasTime1 = array_values($useTime['0']);
        $itemMilAry1 = array_values($itemMilAry['0']);
        $itemMilAry2 = array_sum($itemMilAry['0']);
        
        $detail = array(
                'totalMission' => count($uasRet),
                'totalMil' => round($mil, 2),
                'totalPlane' => count($planes)
        );
        
        $allUseTime = $useTime;
        $allMilTimes = $itemMilAry;
        $planeModels = array();
        foreach ($allUseTime as $key => $value) {
            if (!empty ($key)) {
                $planeModels [] = $key;
            }
        }
        
        $this->returnSuccess(array(
                'fsTotal' => count($uasRet),
                'detail' => $detail,
                'isGeted' => 0,
                'startDate' => $startDate,
                'endDate' => $endDate,
                'showSpace' => $showSpace,
                'planeModel' => $planeModel,
                'filterTime' => $filterTime/60,
                'filterDistance' => ($filterDistance * 1000),
                'planeModels' => $planeModels,
                'chartDate' => json_encode($chartDataTmp),
                'useTime' => json_encode(array_values($useTime['0'])),
                'milTimes' => json_encode(array_values($itemMilAry['0'])),
                'allUseTime' => json_encode($allUseTime),
                'allMilTimes' => json_encode($allMilTimes),
                'milTotal' => $mil
        ));
    }

    /**
     * 生成查询条件语句
     */
    private function _createWhere($user, $uas_serial_id, $startDate, $endDate, $joinname = '', $planeModel)
    {
        $where = '';
        $phoneIn = '';

        if (!empty ($joinname))
            $joinname = $joinname . '.';

        // 通过user获取
        if (!empty ($user)) {
            $userSQL = "select phone from user where nickname like '%$user%'";
            $userList = $this->fetchAll($userSQL);
            if (!empty ($userList)) {
                foreach ($userList as $_user) {
                    $phoneIn .= $_user ['phone'] . '\',\'';
                }
            }

            if (!empty ($phoneIn))
                $phoneIn = rtrim($phoneIn, '\',\'');

            $userWhere = '';
            if (!empty ($phoneIn))
                $userWhere = " phone in ('$phoneIn') ";

            $userWhere .= " or phone like '%$user%'";

            $userWhere = trim($userWhere);
            $userWhere = ltrim($userWhere, 'or');
            $userWhere = "where $userWhere";

            $uasPhoneSQL = "select id from flight_mission $userWhere";

            $flightMissions = $this->fetchAll($uasPhoneSQL);
            $flightMissionIN = "";
            if (!empty ($flightMissions)) {
                foreach ($flightMissions as $ms) {
                    $flightMissionIN .= $ms ['id'] . '\',\'';
                }
            }

            if (!empty ($flightMissionIN))
                $flightMissionIN = rtrim($flightMissionIN, '\',\'');

            $where .= "  {$joinname}flight_mission_id in('$flightMissionIN') ";
        }

        if (!empty ($uas_serial_id)) {
            $uas_serial_id = trim($uas_serial_id);
            if (preg_match('/([^\da-z])/i', $uas_serial_id, $find)) {
                $uasIdList = explode($find [0], $uas_serial_id);
                foreach ($uasIdList as $key => $uasId) {
                    if (empty (trim($uasId)))
                        unset ($uasIdList [$key]);
                }
                $uas_serial_id = implode("','", $uasIdList);
                $where .= " and {$joinname}uas_serial_id in ('$uas_serial_id') ";
            } else {
                $where .= " and {$joinname}uas_serial_id like '%$uas_serial_id%' ";
            }
        }

        if (!empty ($planeModel)) {
            $where .= " and planeModel_id = $planeModel ";
        }

        // 通过飞机编号查询
        // $where .= !empty($uas_serial_id) ? " and {$joinname}uas_serial_id like '%$uas_serial_id%'" : '';
        // $where .= !empty($startDate) ? " and {$joinname}created_at >= '$startDate 00:00:00' " : " and {$joinname}created_at >= '1970-01-01 08:00:00' ";
        $where .= !empty ($startDate) ? " and {$joinname}created_at >= '$startDate 00:00:00' " : '';
        $where .= !empty ($endDate) ? " and {$joinname}created_at <= '$endDate 23:59:59' " : '';

        $where = trim($where);
        $where = ltrim($where, 'and');
        return $where;
    }

    /**
     * 生成所属任务时间段数组
     */
    private function _createChartData($stime = false, $etime = false, $showSpace = 'week')
    {
        $etime = empty ($etime) ? time() : $etime;

        $isuse1970 = !empty ($stime) ? false : true;

        $stime = empty ($stime) ? strtotime('2016-01-03') : $stime;

        $wtime = $stime;
        $dateRet = array();
        $day = 0;
        $ctime = time();

        $_showSpace = $showSpace == 'week' ? 7 : 1;
        while (1) {
            if ($day % $_showSpace == 0)
                if ($showSpace == 'week') {
                    $wtime = $stime + ($day + 7) * 86400;
                    $wtime = $wtime > $ctime ? $ctime : $wtime;
                } else
                    $wtime = $stime + $day * 86400;

            $wkey = date('Y-m-d', $wtime);
            $dtime = $stime + $day * 86400;
            $dkey = date('Y-m-d', $dtime);

            if ($dtime >= $etime)
                break;

            $dateRet [$dkey] = $wkey;
            $day++;
        }

        if ($isuse1970)
            $dateRet = array_merge(array(
                '1970-01-01' => '1970-01-07'
            ), $dateRet);

        return $dateRet;
    }

    /**
     * 处理架次信息
     */
    private function _getStatDetail($uasList, $startTime, $endTime, $showSpace, $filterTime = 5, $filterDistance = 0.5, $getMax = true)
    {
        $startTime = !empty ($startTime) ? strtotime($startTime) : '';
        $endTime = !empty ($endTime) ? strtotime($endTime . " 23:59:59") : '';
        $tmpUasList = array();

        $chartData = $this->_createChartData($startTime, $endTime, $showSpace);

        $totalAry = array();

        foreach ($uasList as $uas) {
            $tmpUasList [$uas ['flight_mission_id']] [] = $uas;
            $totalAry [$uas ['uas_serial_id']] [] = $uas;
        }
        $totalItems = array();
        $dateAry = array();
        foreach ($totalAry as $total) {
            $dateAry = array();
            foreach ($total as $val) {
                $dateAry [] = $val ['created_at'];
            }
            array_multisort($dateAry, SORT_DESC, $total);
            $totalItems [] = $total [0];
        }
        unset ($dateAry);

        $totalMil = 0;
        $totalPlane = count($totalItems);
        $workTime = 0;

        $ret = array();

        $useTime = array();

        $itemMissionAry = array();
        $totalPlaneAry = array();

        $milAry = array();
        $itemMilAry = array();
        $missions = array();

        $totalMissionAry = array();
        $fsTotal = 0;
        $c = 0;
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count list:" . count($tmpUasList) . "\r\n", FILE_APPEND);

        $offcount = 0;
        $offmil = 0;
        $endcount = 0;
        $endmil = 0;

        foreach ($tmpUasList as $_uaslist) {
            $prev = array();
            $sumMil = 0;

            if (count($_uaslist) == 1 ) {
                if( $_uaslist [0] ['is_takeoff'] == 1 ){
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
    
                    $missions [] = $_uaslist [0] ['flight_mission_id'];
                    $planes[$_uaslist [0]['flight_mission_id']] = $_uaslist [0];
                    $plane_ids[] = $_uaslist [0]['uas_serial_id'];
                    $planeSystems[$_uaslist [0]['flight_mission_id']]['uas_serial_id'] = $_uaslist [0]['uas_serial_id'];
    
                    if ($_uaslist [0] ['planeModel_id'] != 3 && $_uaslist [0] ['planeModel_id'] != 8) {
                        if ($_uaslist [0] ['stat_log_time'] > 0) {
                            $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        } else {
                            $missionsF200 [] = $_uaslist [0] ['flight_mission_id'];
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        }
                    } else {
                        $missionsD1000 [] = $_uaslist [0] ['id'];
                        $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                    }
    
                    $sumMil = intval($_uaslist [0] ['stat_log_meter']);
    
                    $totalMil += $_uaslist [0] ['stat_log_meter'];
                    $offmil += $_uaslist [0] ['stat_log_meter'];
                    $offcount = $offcount + 1;
    
                    $fsTotal += 1;
    
                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }
    
                    if (!isset ($useTime [$chartData [$dkey]]))
                        $useTime [$chartData [$dkey]] = 0;
                    $useTime [$chartData [$dkey]] += 1;
    
                    if (!isset ($itemMilAry [$chartData [$dkey]]))
                        $itemMilAry [$chartData [$dkey]] = 0;
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }else{
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    $missions [] = $_uaslist [0] ['flight_mission_id'];
                    $planes[$_uaslist [0]['flight_mission_id']] = $_uaslist [0];
                    $plane_ids[] = $_uaslist [0]['uas_serial_id'];
                    $planeSystems[$_uaslist [0]['flight_mission_id']]['uas_serial_id'] = $_uaslist [0]['uas_serial_id'];
                    
                    if ($_uaslist [0] ['planeModel_id'] != 3 && $_uaslist [0] ['planeModel_id'] != 8) {
                        if ($_uaslist [0] ['stat_log_time'] > 0) {
                            $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        } else {
                            $missionsF200 [] = $_uaslist [0] ['flight_mission_id'];
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        }
                    } else {
                        $missionsD1000 [] = $_uaslist [0] ['id'];
                        $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                    }
                    
                    $sumMil = intval($_uaslist [0] ['stat_log_meter']);
                    
                    $totalMil += $_uaslist [0] ['stat_log_meter'];
                    $offmil += $_uaslist [0] ['stat_log_meter'];
                    $offcount = $offcount + 1;
                    
                    $fsTotal += 1;
                    
                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }
                    
                    if (!isset ($useTime [$chartData [$dkey]]))
                        $useTime [$chartData [$dkey]] = 0;
                    $useTime [$chartData [$dkey]] += 1;
                        
                    if (!isset ($itemMilAry [$chartData [$dkey]]))
                        $itemMilAry [$chartData [$dkey]] = 0;
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
                
            }

            foreach ($_uaslist as $_uas) {

                if (empty ($prev)) {
                    $prev = $_uas;
                    continue;
                }

                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && $_uas ['planeModel_id'] != 3 && $_uas ['planeModel_id'] != 8) {
                    if (((intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value'])) < $filterDistance) && ($prev ['stat_log_meter'] < $filterDistance) && ($prev ['stat_log_time'] < ($filterTime * 60))) {
                        continue;
                    }

                    $missions [] = $_uas ['flight_mission_id'];
                    $planes[$_uas['flight_mission_id']] = $_uas;
                    $plane_ids[] = $_uas['uas_serial_id'];
                    $planeSystems[$_uas['flight_mission_id']]['uas_serial_id'] = $_uas['uas_serial_id'];
                    
                    if($prev ['stat_log_time']>0 && (intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ))>200 ){//飞控跳变,使用飞行日志
                        $workTime += ($prev ['stat_log_time']/3600);
                        $missionsF200s [] = $_uas ['id'];
                        
                        $sumMil = $prev ['stat_log_meter'];
                        $endmil += $prev ['stat_log_meter'];
                        $totalMil += $prev ['stat_log_meter'];
                    }else{                        
                        if($prev ['stat_log_meter']*100/(intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ))<95 ){//飞行日志完整,使用日志时间
                            $missionsF200 [] = $_uas ['flight_mission_id'];
                        }else{
                            $workTime += ($prev ['stat_log_time']/3600);
                        }
                        
                        $missionsF200s [] = $_uas ['id'];
                        
                        $sumMil = intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                        $endmil += intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                        $totalMil += intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                    }
                    
                    $fsTotal += 1;

                    $endcount = $endcount + 1;

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]])) {
                        $useTime [$chartData [$dkey]] = 0;
                    }
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]])) {
                        $itemMilAry [$chartData [$dkey]] = 0;
                    }
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && ($_uas ['planeModel_id'] == 3 || $_uas ['planeModel_id'] == 8)) {
                    if ($prev ['stat_log_meter'] < $filterDistance && $prev ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    $missions [] = $_uas ['flight_mission_id'];
                    $planes[$prev['flight_mission_id']] = $prev;
                    $plane_ids[] = $prev['uas_serial_id'];
                    $planeSystems[$prev['flight_mission_id']]['uas_serial_id'] = $prev['uas_serial_id'];

                    $missionsD1000 [] = $_uas ['id'];

                    $sumMil = intval($prev ['stat_log_meter']);

                    $fsTotal += 1;

                    $totalMil += $prev ['stat_log_meter'];
                    $workTime += ($prev ['stat_log_time'] / 3600);

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]])) {
                        $useTime [$chartData [$dkey]] = 0;
                    }
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]])) {
                        $itemMilAry [$chartData [$dkey]] = 0;
                    }
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
            }
        }

        $missions = array_values($missions);
        $missions = array_unique($missions);

        $chartDataTmp = array_values($chartData);
        $chartDataTmp = array_unique($chartDataTmp);
        $chartDataTmp = array_values($chartDataTmp);
        foreach ($chartDataTmp as $date) {
            if (!isset ($useTime [$date]))
                $useTime [$date] = 0;

            if (!isset ($itemMilAry [$date]))
                $itemMilAry [$date] = 0;
        }
        ksort($useTime);
        ksort($itemMilAry);

        $fsTotal = array_sum($useTime);

        $missionRet = [
            'work_areas' => 0,
            'work_times' => 0
        ];
        $missionF200Ret = [
            'work_areas' => 0,
            'work_times' => 0
        ];

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time workTime:$workTime\r\n", FILE_APPEND);

        if (!empty ($missionsF200)) {
            $missionsF200In = implode(",", $missionsF200);
            $missionsF200Sql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsF200In)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time F200_mid:$missionsF200Sql\r\n", FILE_APPEND);
            $missionF200Ret = $this->fetchOne($missionsF200Sql);
        }

        if (!empty ($missions)) {
            $missionsIn = implode(",", $missions);
            $missionsSql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsIn)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$missionsSql\r\n", FILE_APPEND);
            $missionRet = $this->fetchOne($missionsSql);
        }

        if (!empty ($plane_ids)) {
            $planeIdsIn = implode("','", $plane_ids);
            $planeIdsSql = "select p.uas_serial_id,s.system_name from plane as p left join bind_plane_system as b on p.id=b.plane_id left join subsystem_info as s on b.system_id=s.id where p.uas_serial_id in ('$planeIdsIn');";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "plane sql:$planeIdsSql\r\n", FILE_APPEND);
            $planeRets = $this->fetchAll($planeIdsSql);
            $planeSystem = array();
            foreach ($planeRets as $planeRet) {
                $planeSystem[$planeRet['uas_serial_id']] = $planeRet['system_name'];
            }
            foreach ($planeSystems as $key => $plane_id) {
                $planeSystems[$key]['system_name'] = $planeSystem[$plane_id['uas_serial_id']];
            }
        }

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count offmil:$offmil, offcount:$offcount\r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count endmil:$endmil, endcount:$endcount \r\n", FILE_APPEND);

        $m = $workTime;
        return array(
            'missionList' => $missions,
            'planeList' => $planes,
            'planeSystem' => $planeSystems,
            'totalPlane' => $totalPlane,
            'totalMil' => round($totalMil, 2),
            'totalMission' => $fsTotal,
            'chartDate' => $chartDataTmp,
            'detail' => array(
                'useTime' => array_values($useTime),
                'milTimes' => array_values($itemMilAry),
                'milTotal' => array_sum($itemMilAry),
                'fsTotal' => $fsTotal,
                'workArea' => round($missionRet ['work_areas'], 2),
                'workTime' => round(($missionF200Ret ['work_times'] / 60) + $workTime, 2)
            )
        );
    }

    /**
     * 处理架次信息
     */
    private function _getStatCount($uasList, $startTime, $endTime, $showSpace, $filterTime = 5, $filterDistance = 0.5, $getMax = true)
    {
        $startTime = !empty ($startTime) ? strtotime($startTime) : '';
        $endTime = !empty ($endTime) ? strtotime($endTime . " 23:59:59") : '';
        $tmpUasList = array();

        $chartData = $this->_createChartData($startTime, $endTime, $showSpace);

        $totalAry = array();

        foreach ($uasList as $uas) {

            if (empty($uas['province'])) {
                $uas['province'] = 'null';
            }

            $tmpUasList [$uas ['flight_mission_id']] [] = $uas;
            $totalAry [$uas ['uas_serial_id']] [] = $uas;
        }
        $totalItems = array();
        $dateAry = array();
        foreach ($totalAry as $total) {
            $dateAry = array();
            foreach ($total as $val) {
                $dateAry [] = $val ['created_at'];
            }
            array_multisort($dateAry, SORT_DESC, $total);
            $totalItems [] = $total [0];
        }
        unset ($dateAry);

        $totalMil = 0;
        $totalPlane = count($totalItems);
        $workTime = 0;

        $ret = array();

        $useTime = array();

        $itemMissionAry = array();
        $totalPlaneAry = array();

        $milAry = array();
        $itemMilAry = array();
        $missions = array();

        $totalMissionAry = array();
        $missionProvince = array();
        $fsTotal = 0;
        $c = 0;
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count list:" . count($tmpUasList) . "\r\n", FILE_APPEND);

        $offcount = 0;
        $offmil = 0;
        $endcount = 0;
        $endmil = 0;

        foreach ($tmpUasList as $_uaslist) {
            $prev = array();
            $sumMil = 0;

            if (count($_uaslist) == 1) {
                if($_uaslist [0] ['is_takeoff'] == 1){
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    $missions [] = $_uaslist [0] ['flight_mission_id'];
                    $planes[$_uaslist [0]['flight_mission_id']] = $_uaslist [0];
                    
                    if ($_uaslist [0] ['planeModel_id'] != 3 && $_uaslist [0] ['planeModel_id'] != 8) {
                        if ($_uaslist [0] ['stat_log_time'] > 0) {
                            $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        } else {
                            $missionsF200 [] = $_uaslist [0] ['flight_mission_id'];
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        }
                    } else {
                        $missionsD1000 [] = $_uaslist [0] ['id'];
                        $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                    }
                    
                    $sumMil = intval ( $_uaslist [0] ['stat_log_meter'] );
                    
                    if(isset($missionProvince[$_uaslist [0] ['province']])){
                        $missionProvince[$_uaslist [0] ['province']]['sumMil'] = $missionProvince[$_uaslist [0] ['province']]['sumMil'] + $_uaslist [0] ['stat_log_meter'];
                        $missionProvince[$_uaslist [0] ['province']]['workTime'] = $missionProvince[$_uaslist [0] ['province']]['workTime'] + ($_uaslist [0] ['stat_log_time'] / 3600);
                        $missionProvince[$_uaslist [0] ['province']]['fsTotal'] = $missionProvince[$_uaslist [0] ['province']]['fsTotal'] + 1;
                    }else{
                        $missionProvince[$_uaslist [0] ['province']]['sumMil'] = $_uaslist [0] ['stat_log_meter'];
                        $missionProvince[$_uaslist [0] ['province']]['workTime'] = $_uaslist [0] ['stat_log_time'] / 3600;
                        $missionProvince[$_uaslist [0] ['province']]['fsTotal'] = 1;
                    }
    
                    $totalMil += $_uaslist [0] ['stat_log_meter'];
                    $offmil += $_uaslist [0] ['stat_log_meter'];
                    $offcount = $offcount + 1;
    
                    $fsTotal += 1;
    
                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }
    
                    if (!isset ($useTime [$chartData [$dkey]]))
                        $useTime [$chartData [$dkey]] = 0;
                    $useTime [$chartData [$dkey]] += 1;
    
                    if (!isset ($itemMilAry [$chartData [$dkey]]))
                        $itemMilAry [$chartData [$dkey]] = 0;
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }else{
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    $missions [] = $_uaslist [0] ['flight_mission_id'];
                    $planes[$_uaslist [0]['flight_mission_id']] = $_uaslist [0];
                    
                    if ($_uaslist [0] ['planeModel_id'] != 3 && $_uaslist [0] ['planeModel_id'] != 8) {
                        if ($_uaslist [0] ['stat_log_time'] > 0) {
                            $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        } else {
                            $missionsF200 [] = $_uaslist [0] ['flight_mission_id'];
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        }
                    } else {
                        $missionsD1000 [] = $_uaslist [0] ['id'];
                        $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                    }
                    
                    $sumMil = intval ( $_uaslist [0] ['stat_log_meter'] );
                    
                    if(isset($missionProvince[$_uaslist [0] ['province']])){
                        $missionProvince[$_uaslist [0] ['province']]['sumMil'] = $missionProvince[$_uaslist [0] ['province']]['sumMil'] + $_uaslist [0] ['stat_log_meter'];
                        $missionProvince[$_uaslist [0] ['province']]['workTime'] = $missionProvince[$_uaslist [0] ['province']]['workTime'] + ($_uaslist [0] ['stat_log_time'] / 3600);
                        $missionProvince[$_uaslist [0] ['province']]['fsTotal'] = $missionProvince[$_uaslist [0] ['province']]['fsTotal'] + 1;
                    }else{
                        $missionProvince[$_uaslist [0] ['province']]['sumMil'] = $_uaslist [0] ['stat_log_meter'];
                        $missionProvince[$_uaslist [0] ['province']]['workTime'] = $_uaslist [0] ['stat_log_time'] / 3600;
                        $missionProvince[$_uaslist [0] ['province']]['fsTotal'] = 1;
                    }
                    
                    $totalMil += $_uaslist [0] ['stat_log_meter'];
                    $offmil += $_uaslist [0] ['stat_log_meter'];
                    $offcount = $offcount + 1;
                    
                    $fsTotal += 1;
                    
                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }
                    
                    if (!isset ($useTime [$chartData [$dkey]]))
                        $useTime [$chartData [$dkey]] = 0;
                    $useTime [$chartData [$dkey]] += 1;
                        
                    if (!isset ($itemMilAry [$chartData [$dkey]]))
                        $itemMilAry [$chartData [$dkey]] = 0;
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
            }

            foreach ($_uaslist as $_uas) {

                if (empty ($prev)) {
                    $prev = $_uas;
                    continue;
                }

                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && $_uas ['planeModel_id'] != 3 && $_uas ['planeModel_id'] != 8) {
                    if (((intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value'])) < $filterDistance) && ($prev ['stat_log_meter'] < $filterDistance) && ($prev ['stat_log_time'] < ($filterTime * 60))) {
                        continue;
                    }
                    
                    $missions [] = $_uas ['flight_mission_id'];
                    $planes [$_uas ['flight_mission_id']] = $_uas;
                    
                    if($prev ['stat_log_time']>0 && (intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ))>200 ){//飞控跳变,使用飞行日志
                        $workTime += ($prev ['stat_log_time']/3600);
                        $missionsF200s [] = $_uas ['id'];
                        
                        $sumMil = $prev ['stat_log_meter'];
                        $endmil += $prev ['stat_log_meter'];
                        $totalMil += $prev ['stat_log_meter'];
                        
                        if(isset($missionProvince[$prev['province']])){
                            $missionProvince[$prev['province']]['sumMil'] = $missionProvince[$prev['province']]['sumMil'] + $prev['stat_log_meter'];
                            $missionProvince[$prev['province']]['workTime'] = $missionProvince[$prev['province']]['workTime'] + ($prev['stat_log_time'] / 3600);
                            $missionProvince[$prev['province']]['fsTotal'] = $missionProvince[$prev['province']]['fsTotal'] + 1;
                        }else{
                            $missionProvince[$prev['province']]['sumMil'] = intval ( $prev['stat_log_meter'] );
                            $missionProvince[$prev['province']]['workTime'] = $prev['stat_log_time'] / 3600;
                            $missionProvince[$prev['province']]['fsTotal'] = 1;
                        }
                    }else{
                        if($prev ['stat_log_meter']*100/(intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ))<95 ){//飞行日志完整,使用日志时间
                            $missionsF200 [] = $_uas ['flight_mission_id'];
                        }else{
                            $workTime += ($prev ['stat_log_time']/3600);
                        }
                        
                        $missionsF200s [] = $_uas ['id'];
                        
                        $sumMil = intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                        $endmil += intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                        $totalMil += intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                        
                        if(isset($missionProvince[$prev['province']])){
                            $missionProvince[$prev['province']]['sumMil'] = $missionProvince[$prev['province']]['sumMil'] + (intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ));
                            $missionProvince[$prev['province']]['workTime'] = $missionProvince[$prev['province']]['workTime'] + 0;
                            
                            if($prev ['stat_log_meter']*100/(intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ))<95 ){
                                $missionProvince[$prev['province']]['workTime'] = $missionProvince[$prev['province']]['workTime'] + 0;
                            }else{
                                $missionProvince[$prev['province']]['workTime'] = $missionProvince[$prev['province']]['workTime'] + ($prev ['stat_log_time']/3600);//飞行日志完整,使用日志时间
                            }
                            $missionProvince[$prev['province']]['fsTotal'] = $missionProvince[$prev['province']]['fsTotal'] + 1;
                        }else{
                            $missionProvince[$prev['province']]['sumMil'] = intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                            $missionProvince[$prev['province']]['workTime'] = 0;
                            
                            if($prev ['stat_log_meter']*100/(intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ))<95 ){
                                $missionProvince[$prev['province']]['workTime'] = 0;
                            }else{
                                $missionProvince[$prev['province']]['workTime'] = ($prev ['stat_log_time']/3600);//飞行日志完整,使用日志时间
                            }
                            $missionProvince[$prev['province']]['fsTotal'] = 1;
                        }
                    }
                    
                    $fsTotal += 1;

                    $endcount = $endcount + 1;

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]])) {
                        $useTime [$chartData [$dkey]] = 0;
                    }
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]])) {
                        $itemMilAry [$chartData [$dkey]] = 0;
                    }
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && ($_uas ['planeModel_id'] == 3 || $_uas ['planeModel_id'] == 8)) {
                    if ($prev ['stat_log_meter'] < $filterDistance && $prev ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    $missions [] = $_uas ['flight_mission_id'];
                    $planes [$prev ['flight_mission_id']] = $prev;
                    $missionsD1000 [] = $_uas ['id'];
                    
                    $sumMil = intval ( $prev ['stat_log_meter'] );
                    
                    if(isset($missionProvince[$prev['province']])){
                        $missionProvince[$prev['province']]['sumMil'] = $missionProvince[$prev['province']]['sumMil'] + $prev['stat_log_meter'];
                        $missionProvince[$prev['province']]['workTime'] = $missionProvince[$prev['province']]['workTime'] + ($prev['stat_log_time'] / 3600);
                        $missionProvince[$prev['province']]['fsTotal'] = $missionProvince[$prev['province']]['fsTotal'] + 1;
                    }else{
                        $missionProvince[$prev['province']]['sumMil'] = intval ( $prev['stat_log_meter'] );
                        $missionProvince[$prev['province']]['workTime'] = $prev['stat_log_time'] / 3600;
                        $missionProvince[$prev['province']]['fsTotal'] = 1;
                    }

                    $fsTotal += 1;

                    $totalMil += $prev ['stat_log_meter'];
                    $workTime += ($prev ['stat_log_time'] / 3600);

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime [$chartData [$dkey]])) {
                        $useTime [$chartData [$dkey]] = 0;
                    }
                    $useTime [$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry [$chartData [$dkey]])) {
                        $itemMilAry [$chartData [$dkey]] = 0;
                    }
                    $itemMilAry [$chartData [$dkey]] += $sumMil;
                }
            }
        }

        $missions = array_values($missions);
        $missions = array_unique($missions);

        $chartDataTmp = array_values($chartData);
        $chartDataTmp = array_unique($chartDataTmp);
        $chartDataTmp = array_values($chartDataTmp);
        foreach ($chartDataTmp as $date) {
            if (!isset ($useTime [$date]))
                $useTime [$date] = 0;

            if (!isset ($itemMilAry [$date]))
                $itemMilAry [$date] = 0;
        }
        ksort($useTime);
        ksort($itemMilAry);

//         $fsTotal = array_sum ( $useTime );

        $missionRet = [
            'work_areas' => 0,
            'work_times' => 0
        ];
        $missionF200Ret = [
            'work_areas' => 0,
            'work_times' => 0
        ];

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time workTime:$workTime\r\n", FILE_APPEND);

        if (!empty ($missionsF200)) {
            $missionsF200In = implode(",", $missionsF200);
            $missionsF200Sql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsF200In)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time F200_mid:$missionsF200Sql\r\n", FILE_APPEND);
            $missionF200Ret = $this->fetchOne($missionsF200Sql);

            $provinceF200Sql = "select sum(work_area) as work_areas,sum(work_time) as work_times,province from flight_mission where id in($missionsF200In) GROUP BY province";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$provinceF200Sql\r\n", FILE_APPEND);
            $provinceF200Ret = $this->fetchAll($provinceF200Sql);
        }

        foreach ($provinceF200Ret as $provinceF200) {
            if (empty($provinceF200['province'])) {
                $provinceF200['province'] = 'null';
            }
            if (isset($missionProvince[$provinceF200['province']])) {
                $missionProvince[$provinceF200['province']]['workTime'] = $missionProvince[$provinceF200['province']]['workTime'] + ($provinceF200['work_times'] / 60);
            } else {
                $missionProvince[$provinceF200['province']]['sumMil'] = 0;
                $missionProvince[$provinceF200['province']]['workTime'] = $provinceF200['work_times'] / 60;
                $missionProvince[$provinceF200['province']]['fsTotal'] = 0;
            }

        }

        if (!empty ($missions)) {
            $missionsIn = implode(",", $missions);
            $missionsSql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsIn)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$missionsSql\r\n", FILE_APPEND);
            $missionRet = $this->fetchOne($missionsSql);

            $provinceSql = "select sum(work_area) as work_areas,sum(work_time) as work_times,province from flight_mission where id in($missionsIn) GROUP BY province";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$provinceSql\r\n", FILE_APPEND);
            $provinceRet = $this->fetchAll($provinceSql);
        }

        foreach ($provinceRet as $province) {
            if (empty($province['province'])) {
                $province['province'] = 'null';
            }
            if (isset($missionProvince[$province['province']])) {
                $missionProvince[$province['province']]['work_areas'] = $province['work_areas'];
            } else {
                $missionProvince[$province['province']]['sumMil'] = 0;
                $missionProvince[$province['province']]['fsTotal'] = 0;
                $missionProvince[$province['province']]['work_areas'] = $province['work_areas'];
            }

        }

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count offmil:$offmil, offcount:$offcount\r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count endmil:$endmil, endcount:$endcount \r\n", FILE_APPEND);

        $m = $workTime;
        return array(
            'missionList' => $missions,
            'planeList' => $planes,
            'totalPlane' => $totalPlane,
            'totalMil' => round($totalMil, 2),
            'totalMission' => $fsTotal,
            'chartDate' => $chartDataTmp,
            'provinceList' => $missionProvince,
            'detail' => array(
                'useTime' => array_values($useTime),
                'milTimes' => array_values($itemMilAry),
                'milTotal' => array_sum($itemMilAry),
                'fsTotal' => $fsTotal,
                'workArea' => round($missionRet ['work_areas'], 2),
                'workTime' => round(($missionF200Ret ['work_times'] / 60) + $workTime, 2)
            )
        );
    }

    /**
     * 处理架次信息
     */
    private function _getStatLine($uasList, $startTime, $endTime, $showSpace, $filterTime = 5, $filterDistance = 0.5, $getMax = true)
    {
        $startTime = !empty ($startTime) ? strtotime($startTime) : '';
        $endTime = !empty ($endTime) ? strtotime($endTime . " 23:59:59") : '';
        $tmpUasList = array();

        $chartData = $this->_createChartData($startTime, $endTime, $showSpace);

        $totalAry = array();

        foreach ($uasList as $uas) {

            if (empty ($uas ['province'])) {
                $uas ['province'] = 'null';
            }

            $tmpUasList [$uas ['flight_mission_id']] [] = $uas;
            $totalAry [$uas ['uas_serial_id']] [] = $uas;
        }
        $totalItems = array();
        $dateAry = array();
        foreach ($totalAry as $total) {
            $dateAry = array();
            foreach ($total as $val) {
                $dateAry [] = $val ['created_at'];
            }
            array_multisort($dateAry, SORT_DESC, $total);
            $totalItems [] = $total [0];
        }
        unset ($dateAry);

        $totalMil = 0;
        $totalPlane = count($totalItems);
        $workTime = 0;

        $ret = array();

        $useTime = array();

        $itemMissionAry = array();
        $totalPlaneAry = array();

        $milAry = array();
        $itemMilAry = array();
        $missions = array();

        $totalMissionAry = array();
        $missionProvince = array();
        $fsTotal = 0;
        $c = 0;
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count list:" . count($tmpUasList) . "\r\n", FILE_APPEND);

        $offcount = 0;
        $offmil = 0;
        $endcount = 0;
        $endmil = 0;

        foreach ($tmpUasList as $_uaslist) {
            $prev = array();
            $sumMil = 0;

            if (count($_uaslist) == 1) {
                if($_uaslist [0] ['is_takeoff'] == 1){
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    $missions [] = $_uaslist [0] ['flight_mission_id'];
    
                    if ($_uaslist [0] ['planeModel_id'] != 3 && $_uaslist [0] ['planeModel_id'] != 8) {
                        if ($_uaslist [0] ['stat_log_time'] > 0) {
                            $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        } else {
                            $missionsF200 [] = $_uaslist [0] ['flight_mission_id'];
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        }
                    } else {
                        $missionsD1000 [] = $_uaslist [0] ['id'];
                        $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                    }
    
                    $sumMil = intval($_uaslist [0] ['stat_log_meter']);
    
                    $totalMil += $_uaslist [0] ['stat_log_meter'];
                    $offmil += $_uaslist [0] ['stat_log_meter'];
                    $offcount = $offcount + 1;
    
                    $fsTotal += 1;
    
                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }
    
                    if (!isset ($useTime['0'] [$chartData [$dkey]])) {
                        $useTime['0'] [$chartData [$dkey]] = 0;
                    }
                    $useTime['0'] [$chartData [$dkey]] += 1;
    
                    if (!isset ($useTime[$_uaslist [0] ['planeModel_id']] [$chartData [$dkey]])) {
                        $useTime[$_uaslist [0] ['planeModel_id']] [$chartData [$dkey]] = 0;
                    }
                    $useTime[$_uaslist [0] ['planeModel_id']] [$chartData [$dkey]] += 1;
    
                    if (!isset ($itemMilAry['0'] [$chartData [$dkey]])) {
                        $itemMilAry['0'][$chartData [$dkey]] = 0;
                    }
                    $itemMilAry['0'][$chartData [$dkey]] += $sumMil;
    
                    if (!isset ($itemMilAry[$_uaslist [0] ['planeModel_id']] [$chartData [$dkey]])) {
                        $itemMilAry[$_uaslist [0] ['planeModel_id']][$chartData [$dkey]] = 0;
                    }
                    $itemMilAry[$_uaslist [0] ['planeModel_id']][$chartData [$dkey]] += $sumMil;
                }else{
                    if ($_uaslist [0] ['stat_log_meter'] < $filterDistance && $_uaslist [0] ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    
                    $missions [] = $_uaslist [0] ['flight_mission_id'];
                    
                    if ($_uaslist [0] ['planeModel_id'] != 3 && $_uaslist [0] ['planeModel_id'] != 8) {
                        if ($_uaslist [0] ['stat_log_time'] > 0) {
                            $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        } else {
                            $missionsF200 [] = $_uaslist [0] ['flight_mission_id'];
                            $missionsF200s [] = $_uaslist [0] ['id'];
                        }
                    } else {
                        $missionsD1000 [] = $_uaslist [0] ['id'];
                        $workTime += ($_uaslist [0] ['stat_log_time'] / 3600);
                    }
                    
                    $sumMil = intval($_uaslist [0] ['stat_log_meter']);
                    
                    $totalMil += $_uaslist [0] ['stat_log_meter'];
                    $offmil += $_uaslist [0] ['stat_log_meter'];
                    $offcount = $offcount + 1;
                    
                    $fsTotal += 1;
                    
                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }
                    
                    if (!isset ($useTime['0'] [$chartData [$dkey]])) {
                        $useTime['0'] [$chartData [$dkey]] = 0;
                    }
                    $useTime['0'] [$chartData [$dkey]] += 1;
                    
                    if (!isset ($useTime[$_uaslist [0] ['planeModel_id']] [$chartData [$dkey]])) {
                        $useTime[$_uaslist [0] ['planeModel_id']] [$chartData [$dkey]] = 0;
                    }
                    $useTime[$_uaslist [0] ['planeModel_id']] [$chartData [$dkey]] += 1;
                    
                    if (!isset ($itemMilAry['0'] [$chartData [$dkey]])) {
                        $itemMilAry['0'][$chartData [$dkey]] = 0;
                    }
                    $itemMilAry['0'][$chartData [$dkey]] += $sumMil;
                    
                    if (!isset ($itemMilAry[$_uaslist [0] ['planeModel_id']] [$chartData [$dkey]])) {
                        $itemMilAry[$_uaslist [0] ['planeModel_id']][$chartData [$dkey]] = 0;
                    }
                    $itemMilAry[$_uaslist [0] ['planeModel_id']][$chartData [$dkey]] += $sumMil;
                }
            }

            foreach ($_uaslist as $_uas) {

                if (empty ($prev)) {
                    $prev = $_uas;
                    continue;
                }

                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && $_uas ['planeModel_id'] != 3 && $_uas ['planeModel_id'] != 8) {
                    if (((intval($_uas ['uas_odometer_value']) - intval($prev ['uas_odometer_value'])) < $filterDistance) && ($prev ['stat_log_meter'] < $filterDistance) && ($prev ['stat_log_time'] < ($filterTime * 60))) {
                        continue;
                    }
                    $missions [] = $_uas ['flight_mission_id'];
                    
                    if($prev ['stat_log_time']>0 && (intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ))>200 ){//飞控跳变,使用飞行日志
                        $workTime += ($prev ['stat_log_time']/3600);
                        $missionsF200s [] = $_uas ['id'];
                        
                        $sumMil = $prev ['stat_log_meter'];
                        $endmil += $prev ['stat_log_meter'];
                        $totalMil += $prev ['stat_log_meter'];
                    }else{
                        if($prev ['stat_log_meter']*100/(intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] ))<95 ){//飞行日志完整,使用日志时间
                            $missionsF200 [] = $_uas ['flight_mission_id'];
                        }else{
                            $workTime += ($prev ['stat_log_time']/3600);
                        }
                        
                        $missionsF200s [] = $_uas ['id'];
                        
                        $sumMil = intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                        $endmil += intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                        $totalMil += intval ( $_uas ['uas_odometer_value'] ) - intval ( $prev ['uas_odometer_value'] );
                    }
                    
                    $fsTotal += 1;

                    $endcount = $endcount + 1;

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime['0'][$chartData [$dkey]])) {
                        $useTime['0'][$chartData [$dkey]] = 0;
                    }
                    $useTime['0'][$chartData [$dkey]] += 1;

                    if (!isset ($useTime[$_uas ['planeModel_id']][$chartData [$dkey]])) {
                        $useTime[$_uas ['planeModel_id']][$chartData [$dkey]] = 0;
                    }
                    $useTime[$_uas ['planeModel_id']][$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry['0'][$chartData [$dkey]])) {
                        $itemMilAry['0'][$chartData [$dkey]] = 0;
                    }
                    $itemMilAry['0'][$chartData [$dkey]] += $sumMil;

                    if (!isset ($itemMilAry[$_uas ['planeModel_id']][$chartData [$dkey]])) {
                        $itemMilAry[$_uas ['planeModel_id']][$chartData [$dkey]] = 0;
                    }
                    $itemMilAry[$_uas ['planeModel_id']][$chartData [$dkey]] += $sumMil;
                }
                if ($prev ['is_takeoff'] == 1 && empty ($_uas ['is_takeoff']) && ($_uas ['planeModel_id'] == 3 || $_uas ['planeModel_id'] == 8)) {
                    if ($prev ['stat_log_meter'] < $filterDistance && $prev ['stat_log_time'] < ($filterTime * 60)) {
                        continue;
                    }
                    $missions [] = $_uas ['flight_mission_id'];
                    $missionsD1000 [] = $_uas ['id'];

                    $sumMil = intval($prev ['stat_log_meter']);

                    $fsTotal += 1;

                    $totalMil += $prev ['stat_log_meter'];
                    $workTime += ($prev ['stat_log_time'] / 3600);

                    list ($dkey) = explode(' ', $_uas ['created_at']);
                    if (!isset ($chartData [$dkey])) {
                        continue;
                    }

                    if (!isset ($useTime['0'][$chartData [$dkey]])) {
                        $useTime['0'][$chartData [$dkey]] = 0;
                    }
                    $useTime['0'][$chartData [$dkey]] += 1;

                    if (!isset ($useTime[$_uas ['planeModel_id']][$chartData [$dkey]])) {
                        $useTime[$_uas ['planeModel_id']][$chartData [$dkey]] = 0;
                    }
                    $useTime[$_uas ['planeModel_id']][$chartData [$dkey]] += 1;

                    if (!isset ($itemMilAry['0'][$chartData [$dkey]])) {
                        $itemMilAry['0'][$chartData [$dkey]] = 0;
                    }
                    $itemMilAry['0'][$chartData [$dkey]] += $sumMil;

                    if (!isset ($itemMilAry[$_uas ['planeModel_id']][$chartData [$dkey]])) {
                        $itemMilAry[$_uas ['planeModel_id']][$chartData [$dkey]] = 0;
                    }
                    $itemMilAry[$_uas ['planeModel_id']][$chartData [$dkey]] += $sumMil;
                }
            }
        }

        $missions = array_values($missions);
        $missions = array_unique($missions);

        $chartDataTmp = array_values($chartData);
        $chartDataTmp = array_unique($chartDataTmp);
        $chartDataTmp = array_values($chartDataTmp);
        foreach ($chartDataTmp as $date) {
//             if (! isset ( $useTime['0'][$date] )){
//                 $useTime['0'][$date] = 0;
//             }

            foreach ($useTime as $key => $value) {
                if (!isset ($useTime[$key][$date])) {
                    $useTime[$key][$date] = 0;
                }
                if (!isset ($itemMilAry[$key][$date])) {
                    $itemMilAry[$key][$date] = 0;
                }
            }
        }

        foreach ($useTime as $key => $value) {
            ksort($useTime[$key]);
            ksort($itemMilAry[$key]);
        }

        // $fsTotal = array_sum ( $useTime );

        $missionRet = [
            'work_areas' => 0,
            'work_times' => 0
        ];
        $missionF200Ret = [
            'work_areas' => 0,
            'work_times' => 0
        ];

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time workTime:$workTime\r\n", FILE_APPEND);

        if (!empty ($missionsF200)) {
            $missionsF200In = implode(",", $missionsF200);
            $missionsF200Sql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsF200In)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time F200_mid:$missionsF200Sql\r\n", FILE_APPEND);
            $missionF200Ret = $this->fetchOne($missionsF200Sql);
        }

        if (!empty ($missions)) {
            $missionsIn = implode(",", $missions);
            $missionsSql = "select sum(work_area) as work_areas,sum(work_time) as work_times from flight_mission where id in($missionsIn)";
            file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$missionsSql\r\n", FILE_APPEND);
            $missionRet = $this->fetchOne($missionsSql);
        }

        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count offmil:$offmil, offcount:$offcount\r\n", FILE_APPEND);
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "count endmil:$endmil, endcount:$endcount \r\n", FILE_APPEND);

        return array(
            'missionList' => $missions,
            'totalPlane' => $totalPlane,
            'totalMil' => round($totalMil, 2),
            'totalMission' => $fsTotal,
            'chartDate' => $chartDataTmp,
            'detail' => array(
                'useTime' => array_values($useTime['0']),
                'milTimes' => array_values($itemMilAry['0']),
                'allUseTime' => $useTime,
                'allMilTimes' => $itemMilAry,
                'milTotal' => array_sum($itemMilAry['0']),
                'fsTotal' => $fsTotal,
                'workArea' => round($missionRet ['work_areas'], 2),
                'workTime' => round(($missionF200Ret ['work_times'] / 60) + $workTime, 2)
            )
        );
    }


    /******************************   智监控    ***********************************************************/


    public function monitor4newAction()
    {

        //获取token
        $token = $this->request->get('token');
        $user = $this->fetchOne("select id,nickname,icon_url from user where token = '$token'");
        if (empty($user)) {
            $user = $this->fetchOne("select id,nickname,icon_url from user where ios_token = '$token'");
            if (empty($user)) {

                $this->transferErrorPage("权限不足","您的登录口令无效");

            }
        }
        if (empty($user['icon_url'])) {
            $user['icon_url'] = "/images/cloudplay/monitor_asset/user_pic_placehorder.png";
        }

        $cityList = $this->getProvinceInfo(false,true);
        $this->view->setVars([
            'cityList' => $cityList,
            'user' => $user
        ]);

    }

    /**
     * 查询用户列表下的测区信息测区列表动作
     */
    public function requestBlockListAction()
    {
        $start = $this->request->getPost('start');
        $end = $this->request->getPost('end');
        $token = $this->request->getPost('token');
        $name = $this->request->getPost('name');
        $noneTask=$this->request->getPost('none_task');

        $blockWhere="";

        if ($start) {
            $blockWhere .= " created_at>='$start' ";
        }
        if ($end) {
            if (strlen($blockWhere) > 0) {
                $blockWhere .= " and ";
            }
            $blockWhere .= " created_at<='$end' ";
        }
        if ($name) {
            if (strlen($blockWhere) > 0) {
                $blockWhere .= " and ";
            }
            $blockWhere .= " survey_area_name like '%$name%' ";
        }
        if(strlen($blockWhere) <= 0){
            $blockWhere="1=1";
        }

        $sql = "select * from (SELECT temp.*, sum(CASE WHEN task.id IS NULL
  THEN 0
                   ELSE 1 END) AS task_count from (
  SELECT block.id as block_id,block.survey_area_name,
    block.home_lng,block.home_lat,block.created_at,block.survey_area_coordinate_points,block.entry_direction,
    temp.project_name,temp.id as project_id,software_version
  FROM (select * from survey_block where $blockWhere) AS block
    INNER JOIN (
                 SELECT *
                 FROM (
                        SELECT
                          local_id,
                          id,
                          project_name,
                          software_version
                        FROM project
                        WHERE is_removed = 0 AND user_id = (select id from user where token = '$token ')
                        ORDER BY version DESC)
                   AS temp
                 GROUP BY local_id
               ) AS temp ON block.project_id = temp.id
) as temp
left join flight_task as task on temp.block_id=task.survey_block_id
GROUP BY temp.block_id) as temp ";
        $whereSql = "";
        if ($name) {
            $whereSql .= " project_name like'%$name%' ";
        }

        if($noneTask){
            if (strlen($whereSql) > 0) {
                $whereSql .= " and ";
            }
            $whereSql.=" task_count<=0 ";
        }else{
            if (strlen($whereSql) > 0) {
                $whereSql .= " and ";
            }
            $whereSql.=" task_count>0 ";
        }

        if (strlen($whereSql)) {
            $sql .= " where " . $whereSql;
        }
        $sql .= " order by created_at desc";
        $data = $this->fetchAll($sql);
        for($i=0;$i<count($data);$i++){
            if($this->isUseWgs84CS($data[$i]['software_version'])){
                $data[$i]['flight_way_cs']="wgs84";
            }else{
                $data[$i]['flight_way_cs']="gcj02";
            }

        }

        $this->returnJson($data);

    }

    /**
     *
     * 请求任务详情
     * 用于monitor4new页面
     *
     */
    public function requestTaskDetailAction(){
        $task_local_id = $this->request->get('task_local_id');
        if(!empty($task_local_id)){
            $taskInfoSql="SELECT temp.*,project.project_name from (

SELECT survey_block.*,task.task_coordinate_waypoints,task.total_mileage,task.work_time as task_work_time FROM
(

SELECT * from flight_task WHERE local_id='$task_local_id') as task

left join  survey_block on survey_block.id=task.survey_block_id
 ) as temp left JOIN project ON project.id=temp.project_id
";
            $data=$this->fetchOne($taskInfoSql);
            $missionListSql="SELECT
  created_at,
  local_id,
  id as mission_id
FROM flight_mission WHERE flight_task_id='$task_local_id'";
            $missionList=$this->fetchAll($missionListSql);
            //missionList是否在飞行
            for($i=0;$i<count($missionList);$i++){
                $missionList[$i]['is_flying']=$this->isMissionFlying($missionList[$i]['mission_id']);
            }
            if($this->isProjectUseWgs84ByProjectId($data['project_id'])){
                $data['flight_way_cs']="wgs84";
            }else{
                $data['flight_way_cs']="gcj02";
            }

            $data['missionList']=$missionList;
            $this->result2Json($data);
        }else{
            $this->result2Json("Error,empty parameter");
        }
    }



    private function isProjectUseWgs84ByLocalId($projectLocal){
        $sql="select software_version from project where local_id='$projectLocal'";
        $data=$this->fetchOne($sql);
        if($data){
            return $this->isUseWgs84CS($data);
        }
        return true;
    }

    /**
     * mission是否需要纠偏
     * @param $mission_id
     */
    private function isProjectUseWgs84ByProjectId($project_id){
        $sql=" select software_version from project where id=$project_id";
        $data=$this->fetchOne($sql);
        if($data){
            return $this->isUseWgs84CS($data);
        }
        return false;
    }

    private function isUseWgs84CS($data)
    {

        if (!empty($data)) {
            $softwareVersion = $data['software_version'];
            if (!empty($softwareVersion)) {
                $stringArray = explode(' ', $softwareVersion);
                if (count($stringArray) >= 2) {
                    if (strstr($stringArray[0], 'Windows')) {
                        $versionArray = explode('.', $stringArray[1]);
                        if (intval($versionArray[0]) >= 3) {
                            return true;
                        }else{
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    public function ajaxGetAddressByLngLatAction()
    {
        $lng = $this->getPost('lng');
        $lat = $this->getPost('lat');

        $url = 'http://restapi.amap.com/v3/geocode/regeo?output=json&location=' . $lng . ',' . $lat . '&key=6c0fa1f82ce39129a1e5f69b38e69278';

        exit($this->curlRequest($url, 'GET'));
    }



    /**
     * 获取block的统计信息
     */
    public function requestBlockStatAction()
    {

        $token = $this->request->get('token');
        $sql = "SELECT
  temp.block_id,
  sum(CASE WHEN mission.project_id IS NULL
    THEN 0
      ELSE 1 END) AS flight_count,sum(CASE WHEN mission.voyage is NULL then 0 ELSE mission.voyage END ) as voyage
FROM
(SELECT
  m.id,m.project_id,m.voyage,
  sum(CASE WHEN u.id IS NULL
    THEN 0
      ELSE 1 END) AS flytime
FROM flight_mission AS m
  LEFT JOIN uas_status AS u ON u.flight_mission_id = m.id
GROUP BY m.id)
AS mission
  RIGHT JOIN (

               SELECT
                 block.id      AS block_id,
                 temp.local_id AS project_local_id
               FROM survey_block AS block
                 INNER JOIN (
                              SELECT
                                local_id,
                                id
                              FROM (
                                     SELECT
                                       local_id,
                                       id
                                     FROM project
                                     WHERE is_removed = 0 AND user_id = (select id from user where token = '$token')
                                     ORDER BY version DESC)
                                AS temp
                              GROUP BY local_id
                            ) AS temp ON block.project_id = temp.id
             ) AS temp ON temp.project_local_id = mission.project_id
GROUP BY temp.block_id, temp.project_local_id

";
        $data = $this->fetchAll($sql);
        $unfly = 0;
        $total = count($data);
        $voyageTotal = 0;
        $flyTime=0;
        foreach ($data as $item) {

            if ($item['flight_count'] == 0) {
                $unfly++;
            }else{
                $flyTime+=$item['flight_count'];
            }
            $voyageTotal += $item['voyage'];
        }

        //请求该用户下的所有的飞行任务和飞行次数总数

        $this->result2Json([
            'unfly' => $unfly,
            'total' => $total,
            'fly' => ($total - $unfly),
            'voyage' => $voyageTotal,
            'flytime'=>$flyTime
        ]);
    }

    //支持跨域调用
    private function result2Json($data)
    {

        header('Content-type: application/json');
        header('Access-Control-Allow-Origin:*');
        $this->returnJson($data);
    }

    /**
     * 获取我项目下的飞机信息
     * @param $token
     * @return mixed
     */
    public function requestMyPlaneStatAction()
    {

        $token = $this->request->get('token');

        $sql = "SELECT  temp.*,plane.expired_at,plane.warranty_at,plane.user_id FROM (
  SELECT
    uas_serial_id,
    sum(voyage)     AS voyage,
    sum(CASE WHEN landing_method = 0
      THEN 1
        ELSE 0 END) AS landing
  FROM
    (
      SELECT *
      FROM
        (
          SELECT *
          FROM (

                 SELECT local_id
                 FROM project
                 WHERE is_removed = 0 AND user_id = (SELECT id
                                                     FROM user
                                                     WHERE token = '$token')
                 ORDER BY version DESC)
            AS temp
          GROUP BY local_id
        ) AS project

        RIGHT JOIN (


                     SELECT
                       u.uas_serial_id,
                       f.landing_method,
                       f.voyage,
                       f.project_id
                     FROM uas_status u
                       LEFT JOIN flight_mission f ON f.id = u.flight_mission_id
                     WHERE NOT (project_id IS NULL AND project_id = '') AND (u.is_takeoff is null)



                   ) AS uas ON project.local_id = uas.project_id

    ) AS temp
  WHERE local_id IS NOT NULL
  GROUP BY uas_serial_id

) as temp LEFT JOIN plane on plane.uas_serial_id=temp.uas_serial_id";

        $myPlaneSql = "SELECT  temp.*,plane.expired_at,plane.warranty_at,plane.user_id FROM (
  SELECT
    uas_serial_id,
    sum(voyage)     AS voyage,
    sum(CASE WHEN landing_method = 0
      THEN 1
        ELSE 0 END) AS landing
  FROM
    (

      SELECT
        u.uas_serial_id,
        f.landing_method,
        f.voyage,
        f.project_id
      FROM uas_status u
        LEFT JOIN flight_mission AS f ON f.id = u.flight_mission_id
      WHERE NOT (project_id IS NULL AND project_id = '') AND (u.is_takeoff IS NULL)
    ) AS temp
      GROUP BY uas_serial_id
    ) as temp LEFT JOIN plane on plane.uas_serial_id=temp.uas_serial_id
WHERE user_id = (SELECT id FROM user WHERE token = '$token')
";
        $data = $this->fetchAll($sql);
        $myPlaneData=$this->fetchAll($myPlaneSql);
        return $this->returnJson(array('project_plane'=>$data,'my_plane'=>$myPlaneData));

    }


    /**
     * 请求任务列表
     * 包含了下面所属在任务的个数状态。
     */
    public function requestTaskListAction(){
        $token = $this->request->get('token');
        $sql = "SELECT *,sum(CASE WHEN mission_id IS NULL
  THEN 0
             ELSE 1 END) AS mission_count
FROM (
SELECT  task.*,mission.id as mission_id from (
SELECT task.id,task.local_id,task_coordinate_waypoints,block_home_lat,block_home_lng,temp.id as block_id
FROM flight_task AS task INNER JOIN (
                                      SELECT block.id,home_lat as block_home_lat,home_lng as block_home_lng
                                      FROM survey_block AS block
                                        INNER JOIN (
                                                     SELECT id
                                                     FROM (
                                                            SELECT
                                                              local_id,
                                                              id
                                                            FROM project
                                                            WHERE is_removed = 0 AND user_id = (SELECT id
                                                                                                FROM user
                                                                                                WHERE token = '$token ')
                                                            ORDER BY version DESC)
                                                       AS temp
                                                     GROUP BY local_id
                                                   ) AS temp ON block.project_id = temp.id
                                    ) AS temp ON temp.id = task.survey_block_id

) as task LEFT JOIN flight_mission as mission on mission.flight_task_id=task.local_id
) as temp
GROUP BY  temp.id";
        $data = $this->fetchAll($sql);

        for($i=0;$i<count($data);$i++){
            if($data[$i]['mission_count']>0){
                $data[$i]['is_flying']=$this->isTaskFlying($data[$i]['local_id']);
            }else{
                $data[$i]['is_flying']=0;
            }
        }

        $this->result2Json($data);
    }
    
    public function sysCameraTypeAction()
    {
        $loginUser = $this->getMonitorLoginUser();
        
        $system_id = $this->request->get('system_id');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');
        
        $where = '';        
        if (!empty ($startDate)) {
            $where .= " and u.created_at > '$startDate 00:00:00' ";
        }
        
        if (!empty ($endDate)) {
            $where .= " and u.created_at < '$endDate 23:59:59' ";
        }
        
        if ($filterTime !== '0') {
            $filterTime = empty ($filterTime) ? 5 : $filterTime;
            $filterTime = $filterTime*60;
        }
        
        if ($filterDistance !== '0') {
            $filterDistance = empty ($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }
        
        if (!empty ($system_id)) {
            $sql_system = "SELECT p.uas_serial_id FROM bind_plane_system as b,plane as p where b.plane_id=p.id and b.system_id =$system_id";
            $subSerialList = $this->fetchAll($sql_system);
            foreach ($subSerialList as $subSerial) {
                $subSerial_arr [] = $subSerial ['uas_serial_id'];
            }
            $subSerial_ids = implode("','", $subSerial_arr);
            if (!empty ($subSerial_ids)) {
                $where .= " and u.uas_serial_id in ('$subSerial_ids') ";
            } else {
                $where = " and u.uas_serial_id = 'noplane' ";
            }
        }
        
        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = " and f.user_id = " . $loginUser->userId;
        }
        
        $cameraSql = "select count(fmid) as total,camera_type from (select f.id as fmid,count(u.id) as uasid,u.uas_serial_id,
        (max(u.uas_odometer_value)-min(u.uas_odometer_value)) as odometer,
        max(u.stat_log_meter) as log_meter,
        p.planeModel_id,f.camera_type,
        CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_meter)
        ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_meter)
        ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_meter),
        (max(u.uas_odometer_value)-min(u.uas_odometer_value))) END END as mil,
        CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_time)/3600
        ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_time)/3600
        ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_time)/3600,f.work_time/60) END END as work_time,
        max(u.stat_log_time) as time,
        f.work_area,u.province
        from flight_mission f,uas_status u,plane p
        where f.id=u.flight_mission_id and u.uas_serial_id=p.uas_serial_id and p.user_id<>7 and f.user_id not in (10,27,1699,1735) and (u.uas_serial_id like '%FF%' or u.uas_serial_id like '07JD%' or u.uas_serial_id like '11VK%')
        $where $user_type_where $user_where
        group by fmid HAVING (mil>$filterDistance or time>$filterTime) order by fmid) as temp group by camera_type";
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$cameraSql\r\n", FILE_APPEND);
        $cameraType = $this->fetchAll($cameraSql);
        
        
        $this->returnJson(array(
            'cameraType' => json_encode ( $cameraType )
        ) );
    }
    
    public function sysPlaneModelAction()
    {
        $loginUser = $this->getMonitorLoginUser();
        
        $system_id = $this->request->get('system_id');
        $startDate = $this->request->get('startDate');
        $endDate = $this->request->get('endDate');
        $filterTime = $this->request->get('filterTime');
        $filterDistance = $this->request->get('filterDistance');
        
        $where = '';
        if (!empty ($startDate)) {
            $where .= " and u.created_at > '$startDate 00:00:00' ";
        }
        
        if (!empty ($endDate)) {
            $where .= " and u.created_at < '$endDate 23:59:59' ";
        }
        
        if ($filterTime !== '0') {
            $filterTime = empty ($filterTime) ? 5 : $filterTime;
            $filterTime = $filterTime*60;
        }
        
        if ($filterDistance !== '0') {
            $filterDistance = empty ($filterDistance) ? 500 : $filterDistance;
            $filterDistance = $filterDistance / 1000;
        }
        
        if (!empty ($system_id)) {
            $sql_system = "SELECT p.uas_serial_id FROM bind_plane_system as b,plane as p where b.plane_id=p.id and b.system_id =$system_id";
            $subSerialList = $this->fetchAll($sql_system);
            foreach ($subSerialList as $subSerial) {
                $subSerial_arr [] = $subSerial ['uas_serial_id'];
            }
            $subSerial_ids = implode("','", $subSerial_arr);
            if (!empty ($subSerial_ids)) {
                $where .= " and u.uas_serial_id in ('$subSerial_ids') ";
            } else {
                $where = " and u.uas_serial_id = 'noplane' ";
            }
        }
        
        if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $user_type_where = "";
            $user_where = '';
        } else if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = '';
        }if ($loginUser->userRoleId == MonitorLoginUser::USER_ROLE_NORMAL){
            $sql_subSystem = "select p.uas_serial_id from bind_plane_system as s,plane as p where s.plane_id=p.id and s.system_id=" . $loginUser->subsystemId;
            $subSystemList = $this->fetchAll($sql_subSystem);
            foreach ($subSystemList as $subSystem) {
                $subSystem_arr [] = $subSystem['uas_serial_id'];
            }
            $subSystem_ids = implode("','", $subSystem_arr);
            if (!empty ($subSystem_ids)) {
                $user_type_where = "and u.uas_serial_id in ('$subSystem_ids') ";
            } else {
                $user_type_where = "and u.uas_serial_id = 'noplane' ";
            }
            
            $user_where = " and f.user_id = " . $loginUser->userId;
        }
        
        $planeModelSql = "select count(fmid) as total,planeModel_id, m.name from (select f.id as fmid,count(u.id) as uasid,u.uas_serial_id,
        (max(u.uas_odometer_value)-min(u.uas_odometer_value)) as odometer,
        max(u.stat_log_meter) as log_meter,
        p.planeModel_id,f.camera_type,
        CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_meter)
        ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_meter)
        ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_meter),
        (max(u.uas_odometer_value)-min(u.uas_odometer_value))) END END as mil,
        CASE WHEN p.planeModel_id in (3,8) THEN max(u.stat_log_time)/3600
        ELSE CASE WHEN max(u.uas_odometer_value)-min(u.uas_odometer_value)>200 THEN max(u.stat_log_time)/3600
        ELSE if(max(u.stat_log_meter)>((max(u.uas_odometer_value)-min(u.uas_odometer_value))*0.95),max(u.stat_log_time)/3600,f.work_time/60) END END as work_time,
        max(u.stat_log_time) as time,
        f.work_area,u.province
        from flight_mission f,uas_status u,plane p
        where f.id=u.flight_mission_id and u.uas_serial_id=p.uas_serial_id and p.user_id<>7 and f.user_id not in (10,27,1699,1735) and (u.uas_serial_id like '%FF%' or u.uas_serial_id like '07JD%' or u.uas_serial_id like '11VK%')
        $where $user_type_where $user_where
        group by fmid HAVING (mil>$filterDistance or time>$filterTime) order by fmid) as temp 
        LEFT JOIN plane_model AS m ON planeModel_id = m.id
        group by planeModel_id";
        file_put_contents("./log_" . date("Y-m-d") . ".txt", __METHOD__ . date(" Y-m-d H:i:s") . ':' . "time sql:$planeModelSql\r\n", FILE_APPEND);
        $planeModel = $this->fetchAll($planeModelSql);        
        
        $this->returnJson(array(
            'planeModel' => json_encode ( $planeModel )
        ) );
    }

    /**
     * block是否在飞行
     * @param $block_id
     */
    private function isTaskFlying($task_id){

        $filterString=" flight_task_id='$task_id'";
        $sql =$this->getIsFlyingSql($filterString);
        $data = $this->fetchOne($sql);
        if ($data['total'] > 0) {
            return true;
        }
        return false;
    }

    public function phpInfoAction(){
        phpinfo();
    }

}